@insforge/instabox-sdk 0.6.0 → 0.7.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/README.md +63 -19
- package/dist/index.cjs +1172 -85
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +178 -19
- package/dist/index.d.ts +178 -19
- package/dist/index.js +1162 -85
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/skills/instabox/SKILL.md +5 -4
package/dist/index.cjs
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
2
3
|
var __defProp = Object.defineProperty;
|
|
3
4
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
5
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
5
7
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
8
|
var __export = (target, all) => {
|
|
7
9
|
for (var name in all)
|
|
@@ -15,6 +17,14 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
15
17
|
}
|
|
16
18
|
return to;
|
|
17
19
|
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
18
28
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
29
|
|
|
20
30
|
// src/index.ts
|
|
@@ -36,6 +46,7 @@ __export(index_exports, {
|
|
|
36
46
|
LIMIT_CODES: () => LIMIT_CODES,
|
|
37
47
|
MAX_FILE_BYTES: () => MAX_FILE_BYTES,
|
|
38
48
|
MAX_STDIN_BYTES: () => MAX_STDIN_BYTES,
|
|
49
|
+
MAX_UPLOAD_BYTES: () => MAX_UPLOAD_BYTES,
|
|
39
50
|
Sandbox: () => Sandbox,
|
|
40
51
|
isLimitCode: () => isLimitCode
|
|
41
52
|
});
|
|
@@ -293,6 +304,13 @@ function toResult(res, stdout = res.stdout, stderr = res.stderr) {
|
|
|
293
304
|
if (typeof res.error === "string" && res.error) out.error = res.error;
|
|
294
305
|
return out;
|
|
295
306
|
}
|
|
307
|
+
function utf8Text(bytes) {
|
|
308
|
+
try {
|
|
309
|
+
return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
|
|
310
|
+
} catch {
|
|
311
|
+
return void 0;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
296
314
|
var Commands = class {
|
|
297
315
|
/** @internal */
|
|
298
316
|
constructor(http, sandboxId, defaultEnvs) {
|
|
@@ -303,9 +321,43 @@ var Commands = class {
|
|
|
303
321
|
http;
|
|
304
322
|
sandboxId;
|
|
305
323
|
defaultEnvs;
|
|
324
|
+
/**
|
|
325
|
+
* @internal Uploads stdin the exec request cannot carry to a temporary file and returns its path
|
|
326
|
+
* (set by `Sandbox`, which owns the file routes).
|
|
327
|
+
*/
|
|
328
|
+
stageStdin;
|
|
306
329
|
async run(cmd, opts = {}) {
|
|
307
330
|
if (opts.background) return this.startJob(cmd, opts);
|
|
308
|
-
|
|
331
|
+
let o = opts;
|
|
332
|
+
let staged;
|
|
333
|
+
if (opts.stdin !== void 0) {
|
|
334
|
+
const bytes = typeof opts.stdin === "string" ? new TextEncoder().encode(opts.stdin) : opts.stdin;
|
|
335
|
+
if (!(bytes instanceof Uint8Array)) {
|
|
336
|
+
throw new InstaboxError("stdin must be a string or a Uint8Array", { code: "bad_request" });
|
|
337
|
+
}
|
|
338
|
+
const text = bytes.length <= MAX_STDIN_BYTES ? utf8Text(bytes) : void 0;
|
|
339
|
+
if (text !== void 0) o = { ...opts, stdin: text };
|
|
340
|
+
else {
|
|
341
|
+
if (!this.stageStdin) {
|
|
342
|
+
throw new InstaboxError(`stdin is longer than ${MAX_STDIN_BYTES} bytes or not UTF-8 text`, {
|
|
343
|
+
code: "bad_request"
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
staged = await this.stageStdin(bytes, opts.signal);
|
|
347
|
+
const q2 = shellQuote(staged);
|
|
348
|
+
cmd = `exec <${q2} || exit 1
|
|
349
|
+
rm -f -- ${q2}
|
|
350
|
+
${cmd}`;
|
|
351
|
+
o = { ...opts, stdin: void 0 };
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
let r;
|
|
355
|
+
try {
|
|
356
|
+
r = o.onStdout || o.onStderr ? await this.execStream(cmd, o) : await this.exec(cmd, o);
|
|
357
|
+
} finally {
|
|
358
|
+
if (staged) await this.exec(`rm -f -- ${shellQuote(staged)}`, { noHistory: true }).catch(() => {
|
|
359
|
+
});
|
|
360
|
+
}
|
|
309
361
|
if (r.exitCode !== 0) throw new CommandExitError(r);
|
|
310
362
|
return r;
|
|
311
363
|
}
|
|
@@ -419,7 +471,7 @@ var Commands = class {
|
|
|
419
471
|
}
|
|
420
472
|
/** Reads a streamed exec's server-sent events until its `exit` or `error` event. */
|
|
421
473
|
async readEvents(reader, opts, fail) {
|
|
422
|
-
const
|
|
474
|
+
const dec2 = new TextDecoder();
|
|
423
475
|
const out = { stdout: "", stderr: "" };
|
|
424
476
|
let buf = "";
|
|
425
477
|
let event = "";
|
|
@@ -432,7 +484,7 @@ var Commands = class {
|
|
|
432
484
|
throw fail(streamEnded());
|
|
433
485
|
}
|
|
434
486
|
if (chunk.done) throw fail(streamEnded());
|
|
435
|
-
buf +=
|
|
487
|
+
buf += dec2.decode(chunk.value, { stream: true });
|
|
436
488
|
let start = 0;
|
|
437
489
|
for (let nl = buf.indexOf("\n", start); nl >= 0; nl = buf.indexOf("\n", start)) {
|
|
438
490
|
let line = buf.slice(start, nl);
|
|
@@ -576,7 +628,7 @@ ${value}`;
|
|
|
576
628
|
throw new InstaboxError("wait timeoutMs must be greater than 0", { code: "bad_request" });
|
|
577
629
|
const until = opts.timeoutMs === void 0 ? Infinity : Date.now() + opts.timeoutMs;
|
|
578
630
|
const maxWait = Math.max(0, Math.min(JOB_POLL_SEC, Math.floor((this.http.requestTimeout(Infinity) - 5e3) / 1e3)));
|
|
579
|
-
const
|
|
631
|
+
const dec2 = new TextDecoder();
|
|
580
632
|
let stdout = "";
|
|
581
633
|
let off = 0;
|
|
582
634
|
let idle = JOB_IDLE_MIN_MS;
|
|
@@ -595,10 +647,10 @@ ${value}`;
|
|
|
595
647
|
idle = Math.min(idle * 2, JOB_IDLE_MAX_MS);
|
|
596
648
|
} else if (read.bytes.length > 0) idle = JOB_IDLE_MIN_MS;
|
|
597
649
|
off += read.bytes.length;
|
|
598
|
-
await emit(
|
|
650
|
+
await emit(dec2.decode(read.bytes, { stream: true }));
|
|
599
651
|
if (read.bytes.length === JOB_CHUNK) continue;
|
|
600
652
|
if (read.status !== "running") {
|
|
601
|
-
await emit(
|
|
653
|
+
await emit(dec2.decode());
|
|
602
654
|
if (read.exitCode === void 0) {
|
|
603
655
|
throw new InstaboxError(
|
|
604
656
|
`job ${jobId} ended without an exit code (the sandbox restarted or the job was killed)`,
|
|
@@ -873,11 +925,534 @@ var Desktop = class {
|
|
|
873
925
|
}
|
|
874
926
|
};
|
|
875
927
|
|
|
928
|
+
// src/guest.ts
|
|
929
|
+
var TRANSFER_TMP_PREFIX = "/tmp/.instabox-transfer-";
|
|
930
|
+
var STDIN_TMP_PREFIX = "/tmp/.instabox-stdin-";
|
|
931
|
+
var PUSH_MARK = "INSTABOX-PUSH\0";
|
|
932
|
+
var PULL_MARK = "INSTABOX-PULL\0";
|
|
933
|
+
var EXEC_CHUNK_BYTES = 768e3;
|
|
934
|
+
var GUEST_FNS = `fsize() { local n; n=$(wc -c < "$1") && echo $((n)); }
|
|
935
|
+
fmode() { stat -c %a -- "$1" 2>/dev/null || stat -f %Lp -- "$1"; }
|
|
936
|
+
b64() { base64 | tr -d '\\n'; }
|
|
937
|
+
rng() { { dd bs=1 skip="$2" count=0 2>/dev/null; head -c "$3"; } < "$1"; }
|
|
938
|
+
rpe() { readlink -e -- "$1" 2>/dev/null || { [ -e "$1" ] && rpm "$1"; }; }
|
|
939
|
+
rpm() {
|
|
940
|
+
realpath -m -- "$1" 2>/dev/null && return
|
|
941
|
+
local r; r=$(readlink -f -- "$1" 2>/dev/null) && [ -n "$r" ] && { printf '%s\\n' "$r"; return; }
|
|
942
|
+
r=$(CDPATH= cd -P -- "$(dirname -- "$1")" 2>/dev/null && pwd -P) && { printf '%s/%s\\n' "\${r%/}" "$(basename -- "$1")"; return; }
|
|
943
|
+
case $1 in /*) printf '%s\\n' "$1" ;; *) printf '%s\\n' "$PWD/$1" ;; esac
|
|
944
|
+
}
|
|
945
|
+
`;
|
|
946
|
+
var PUSH_CHUNK_SCRIPT = `if [ "$IB_FIRST" = 1 ]; then (umask 077; set -C; base64 -d > "$IB_TMP"); else base64 -d >> "$IB_TMP"; fi
|
|
947
|
+
`;
|
|
948
|
+
var PUSH_FINISH_SCRIPT = `set -eo pipefail
|
|
949
|
+
trap 'rm -f -- "$IB_TMP"' EXIT
|
|
950
|
+
${GUEST_FNS}d=$IB_DEST
|
|
951
|
+
case $d in "~") d=$HOME ;; "~/"*) d=$HOME/\${d#"~/"} ;; esac
|
|
952
|
+
mkdir -p -- "$d"
|
|
953
|
+
tar -xzf "$IB_TMP" -C "$d" --no-same-owner
|
|
954
|
+
printf 'INSTABOX-PUSH\\0ok\\0%s\\0' "$(rpm "$d")"
|
|
955
|
+
`;
|
|
956
|
+
var PULL_START = `${GUEST_FNS}set -eo pipefail
|
|
957
|
+
printf 'INSTABOX-PULL\\0'
|
|
958
|
+
r=$(rpe "$1") || { printf 'missing\\0'; exit 0; }
|
|
959
|
+
[ -d "$r" ] || { printf 'not_a_dir\\0%s\\0' "$r"; exit 0; }
|
|
960
|
+
umask 077
|
|
961
|
+
trap '[ "$ok" = 1 ] || rm -f -- "$2"' EXIT
|
|
962
|
+
COPYFILE_DISABLE=1 tar -czf "$2" -C "$r" .
|
|
963
|
+
printf 'dir\\0%s\\0%s\\0' "$r" "$(fsize "$2")"
|
|
964
|
+
ok=1
|
|
965
|
+
`;
|
|
966
|
+
var PULL_CHUNK = `${GUEST_FNS}set -eo pipefail
|
|
967
|
+
printf 'INSTABOX-PULL\\0'
|
|
968
|
+
rng "$3" "$2" "$4" | b64
|
|
969
|
+
`;
|
|
970
|
+
var PULL_REMOVE = `rm -f -- "$2"`;
|
|
971
|
+
function q(s) {
|
|
972
|
+
return `'${s.replace(/'/g, `'\\''`)}'`;
|
|
973
|
+
}
|
|
974
|
+
function pullCmd(script, ...args) {
|
|
975
|
+
const run2 = `bash -c "$S" _ "$p" ${args.map(q).join(" ")}`;
|
|
976
|
+
return `S=${q(script)}
|
|
977
|
+
p=$IB_PATH; case $p in "~") p=$HOME ;; "~/"*) p=$HOME/\${p#"~/"} ;; esac; case $p in /*) ;; *) p=$PWD/$p ;; esac
|
|
978
|
+
if sudo -n true 2>/dev/null; then exec sudo -n ${run2}; else exec ${run2}; fi`;
|
|
979
|
+
}
|
|
980
|
+
var pullStartCmd = (tmp) => pullCmd(PULL_START, tmp);
|
|
981
|
+
var pullChunkCmd = (tmp, off, n) => pullCmd(PULL_CHUNK, String(off), tmp, String(n));
|
|
982
|
+
var pullRemoveCmd = (tmp) => pullCmd(PULL_REMOVE, tmp);
|
|
983
|
+
function randomHex(bytes = 8) {
|
|
984
|
+
const b = new Uint8Array(bytes);
|
|
985
|
+
const c = globalThis.crypto;
|
|
986
|
+
if (c?.getRandomValues) c.getRandomValues(b);
|
|
987
|
+
else for (let i = 0; i < bytes; i++) b[i] = Math.floor(Math.random() * 256);
|
|
988
|
+
return Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
// src/tar.ts
|
|
992
|
+
var BLOCK = 512;
|
|
993
|
+
var enc2 = new TextEncoder();
|
|
994
|
+
var dec = new TextDecoder();
|
|
995
|
+
function octal(buf, off, width, value) {
|
|
996
|
+
const s = Math.floor(value).toString(8).padStart(width - 1, "0");
|
|
997
|
+
buf.set(enc2.encode(s.slice(-(width - 1))), off);
|
|
998
|
+
buf[off + width - 1] = 0;
|
|
999
|
+
}
|
|
1000
|
+
function putString(buf, off, width, s) {
|
|
1001
|
+
buf.set(enc2.encode(s).subarray(0, width), off);
|
|
1002
|
+
}
|
|
1003
|
+
function isAscii(s) {
|
|
1004
|
+
return /^[\x20-\x7e]*$/.test(s);
|
|
1005
|
+
}
|
|
1006
|
+
function paxRecord(key, value) {
|
|
1007
|
+
const body = ` ${key}=${value}
|
|
1008
|
+
`;
|
|
1009
|
+
const n = enc2.encode(body).length;
|
|
1010
|
+
let len = n + String(n).length;
|
|
1011
|
+
if (String(len).length !== String(n).length) len = n + String(len).length;
|
|
1012
|
+
return `${len}${body}`;
|
|
1013
|
+
}
|
|
1014
|
+
function header(name, type, mode, mtime, size, linkname) {
|
|
1015
|
+
const h = new Uint8Array(BLOCK);
|
|
1016
|
+
putString(h, 0, 100, name);
|
|
1017
|
+
octal(h, 100, 8, mode & 4095);
|
|
1018
|
+
octal(h, 108, 8, 0);
|
|
1019
|
+
octal(h, 116, 8, 0);
|
|
1020
|
+
octal(h, 124, 12, size);
|
|
1021
|
+
octal(h, 136, 12, Math.max(0, mtime));
|
|
1022
|
+
h.fill(32, 148, 156);
|
|
1023
|
+
h[156] = type.charCodeAt(0);
|
|
1024
|
+
putString(h, 157, 100, linkname);
|
|
1025
|
+
putString(h, 257, 6, "ustar\0");
|
|
1026
|
+
putString(h, 263, 2, "00");
|
|
1027
|
+
let sum = 0;
|
|
1028
|
+
for (const b of h) sum += b;
|
|
1029
|
+
const s = sum.toString(8).padStart(6, "0");
|
|
1030
|
+
putString(h, 148, 6, s);
|
|
1031
|
+
h[154] = 0;
|
|
1032
|
+
h[155] = 32;
|
|
1033
|
+
return h;
|
|
1034
|
+
}
|
|
1035
|
+
var USTAR_MAX_SIZE = 8589934591;
|
|
1036
|
+
function headers(e) {
|
|
1037
|
+
const name = e.type === "dir" ? `${e.name}/` : e.name;
|
|
1038
|
+
const link = e.linkname ?? "";
|
|
1039
|
+
const size = e.type === "file" ? e.size ?? 0 : 0;
|
|
1040
|
+
const pax = [];
|
|
1041
|
+
if (enc2.encode(name).length > 100 || !isAscii(name)) pax.push(paxRecord("path", name));
|
|
1042
|
+
if (enc2.encode(link).length > 100 || !isAscii(link)) pax.push(paxRecord("linkpath", link));
|
|
1043
|
+
if (size > USTAR_MAX_SIZE) pax.push(paxRecord("size", String(size)));
|
|
1044
|
+
const type = e.type === "dir" ? "5" : e.type === "symlink" ? "2" : "0";
|
|
1045
|
+
const out = [];
|
|
1046
|
+
if (pax.length) {
|
|
1047
|
+
const data = enc2.encode(pax.join(""));
|
|
1048
|
+
out.push(header("PaxHeader", "x", 420, e.mtime, data.length, ""));
|
|
1049
|
+
out.push(padded(data));
|
|
1050
|
+
}
|
|
1051
|
+
out.push(
|
|
1052
|
+
header(asciiPrefix(name, 100), type, e.mode, e.mtime, size > USTAR_MAX_SIZE ? 0 : size, asciiPrefix(link, 100))
|
|
1053
|
+
);
|
|
1054
|
+
return out;
|
|
1055
|
+
}
|
|
1056
|
+
function asciiPrefix(s, max) {
|
|
1057
|
+
return s.replace(/[^\x20-\x7e]/g, "_").slice(0, max);
|
|
1058
|
+
}
|
|
1059
|
+
function padded(data) {
|
|
1060
|
+
const n = Math.ceil(data.length / BLOCK) * BLOCK;
|
|
1061
|
+
if (n === data.length) return data;
|
|
1062
|
+
const out = new Uint8Array(n);
|
|
1063
|
+
out.set(data);
|
|
1064
|
+
return out;
|
|
1065
|
+
}
|
|
1066
|
+
async function* tarStream(entries) {
|
|
1067
|
+
for await (const e of entries) {
|
|
1068
|
+
for (const h of headers(e)) yield h;
|
|
1069
|
+
if (e.type !== "file") continue;
|
|
1070
|
+
const size = e.size ?? 0;
|
|
1071
|
+
let n = 0;
|
|
1072
|
+
if (e.data) {
|
|
1073
|
+
for await (const chunk of e.data()) {
|
|
1074
|
+
if (n + chunk.length > size) {
|
|
1075
|
+
throw new InstaboxError(`${e.name} grew while it was being uploaded`, { code: "file_changed" });
|
|
1076
|
+
}
|
|
1077
|
+
n += chunk.length;
|
|
1078
|
+
if (chunk.length) yield chunk;
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
if (n !== size) {
|
|
1082
|
+
throw new InstaboxError(`${e.name} shrank while it was being uploaded (${n} of ${size} bytes)`, {
|
|
1083
|
+
code: "file_changed"
|
|
1084
|
+
});
|
|
1085
|
+
}
|
|
1086
|
+
if (size % BLOCK) yield new Uint8Array(BLOCK - size % BLOCK);
|
|
1087
|
+
}
|
|
1088
|
+
yield new Uint8Array(BLOCK * 2);
|
|
1089
|
+
}
|
|
1090
|
+
var ByteReader = class {
|
|
1091
|
+
buf = new Uint8Array(0);
|
|
1092
|
+
it;
|
|
1093
|
+
done = false;
|
|
1094
|
+
constructor(src) {
|
|
1095
|
+
this.it = src[Symbol.asyncIterator]();
|
|
1096
|
+
}
|
|
1097
|
+
async fill() {
|
|
1098
|
+
if (this.done) return false;
|
|
1099
|
+
const r = await this.it.next();
|
|
1100
|
+
if (r.done) {
|
|
1101
|
+
this.done = true;
|
|
1102
|
+
return false;
|
|
1103
|
+
}
|
|
1104
|
+
const chunk = r.value instanceof Uint8Array ? r.value : new Uint8Array(r.value);
|
|
1105
|
+
if (this.buf.length === 0) this.buf = chunk;
|
|
1106
|
+
else {
|
|
1107
|
+
const b = new Uint8Array(this.buf.length + chunk.length);
|
|
1108
|
+
b.set(this.buf);
|
|
1109
|
+
b.set(chunk, this.buf.length);
|
|
1110
|
+
this.buf = b;
|
|
1111
|
+
}
|
|
1112
|
+
return true;
|
|
1113
|
+
}
|
|
1114
|
+
/** Exactly n bytes, or null at a clean end of input before any of them. */
|
|
1115
|
+
async exact(n) {
|
|
1116
|
+
while (this.buf.length < n) {
|
|
1117
|
+
if (!await this.fill()) {
|
|
1118
|
+
if (this.buf.length === 0) return null;
|
|
1119
|
+
throw truncated();
|
|
1120
|
+
}
|
|
1121
|
+
}
|
|
1122
|
+
const out = this.buf.subarray(0, n);
|
|
1123
|
+
this.buf = this.buf.subarray(n);
|
|
1124
|
+
return out;
|
|
1125
|
+
}
|
|
1126
|
+
/** n bytes as they arrive, in chunks. */
|
|
1127
|
+
async *chunks(n) {
|
|
1128
|
+
let left = n;
|
|
1129
|
+
while (left > 0) {
|
|
1130
|
+
if (this.buf.length === 0 && !await this.fill()) throw truncated();
|
|
1131
|
+
const take = Math.min(left, this.buf.length);
|
|
1132
|
+
const out = this.buf.subarray(0, take);
|
|
1133
|
+
this.buf = this.buf.subarray(take);
|
|
1134
|
+
left -= take;
|
|
1135
|
+
yield out;
|
|
1136
|
+
}
|
|
1137
|
+
}
|
|
1138
|
+
async skip(n) {
|
|
1139
|
+
for await (const _ of this.chunks(n)) void _;
|
|
1140
|
+
}
|
|
1141
|
+
};
|
|
1142
|
+
function truncated() {
|
|
1143
|
+
return new InstaboxError("the archive from the sandbox ended early", { code: "file_changed", retryable: true });
|
|
1144
|
+
}
|
|
1145
|
+
function invalidArchive(why) {
|
|
1146
|
+
return new InstaboxError(`the archive from the sandbox is not valid tar: ${why}`, { code: "invalid_response" });
|
|
1147
|
+
}
|
|
1148
|
+
function cstring(b) {
|
|
1149
|
+
const z = b.indexOf(0);
|
|
1150
|
+
return dec.decode(z < 0 ? b : b.subarray(0, z));
|
|
1151
|
+
}
|
|
1152
|
+
function number(b) {
|
|
1153
|
+
if (b[0] & 128) {
|
|
1154
|
+
let n = b[0] & 127;
|
|
1155
|
+
for (let i = 1; i < b.length; i++) n = n * 256 + b[i];
|
|
1156
|
+
return n;
|
|
1157
|
+
}
|
|
1158
|
+
const s = cstring(b).trim();
|
|
1159
|
+
if (s === "") return 0;
|
|
1160
|
+
if (!/^[0-7]+$/.test(s)) throw invalidArchive(`bad number ${JSON.stringify(s)}`);
|
|
1161
|
+
return parseInt(s, 8);
|
|
1162
|
+
}
|
|
1163
|
+
function parsePax(data) {
|
|
1164
|
+
const out = {};
|
|
1165
|
+
let off = 0;
|
|
1166
|
+
while (off < data.length) {
|
|
1167
|
+
const sp = data.indexOf(32, off);
|
|
1168
|
+
if (sp < 0) break;
|
|
1169
|
+
const len = parseInt(dec.decode(data.subarray(off, sp)), 10);
|
|
1170
|
+
if (!Number.isSafeInteger(len) || len <= 0 || off + len > data.length) throw invalidArchive("bad PAX record");
|
|
1171
|
+
const rec = dec.decode(data.subarray(sp + 1, off + len - 1));
|
|
1172
|
+
const eq = rec.indexOf("=");
|
|
1173
|
+
if (eq > 0) out[rec.slice(0, eq)] = rec.slice(eq + 1);
|
|
1174
|
+
off += len;
|
|
1175
|
+
}
|
|
1176
|
+
return out;
|
|
1177
|
+
}
|
|
1178
|
+
async function* untarStream(src) {
|
|
1179
|
+
const r = new ByteReader(src);
|
|
1180
|
+
let pax = {};
|
|
1181
|
+
let longName;
|
|
1182
|
+
let longLink;
|
|
1183
|
+
for (; ; ) {
|
|
1184
|
+
const h = await r.exact(BLOCK);
|
|
1185
|
+
if (h === null) return;
|
|
1186
|
+
if (h.every((b) => b === 0)) return;
|
|
1187
|
+
let sum = 0;
|
|
1188
|
+
for (let i = 0; i < BLOCK; i++) sum += i >= 148 && i < 156 ? 32 : h[i];
|
|
1189
|
+
if (sum !== number(h.subarray(148, 156))) throw invalidArchive("bad header checksum");
|
|
1190
|
+
const type = String.fromCharCode(h[156]);
|
|
1191
|
+
let size = number(h.subarray(124, 136));
|
|
1192
|
+
const magic = dec.decode(h.subarray(257, 263));
|
|
1193
|
+
let name = cstring(h.subarray(0, 100));
|
|
1194
|
+
if (magic === "ustar\0") {
|
|
1195
|
+
const prefix = cstring(h.subarray(345, 500));
|
|
1196
|
+
if (prefix) name = `${prefix}/${name}`;
|
|
1197
|
+
}
|
|
1198
|
+
let linkname = cstring(h.subarray(157, 257));
|
|
1199
|
+
const mode = number(h.subarray(100, 108)) & 4095;
|
|
1200
|
+
if (type === "x" || type === "g" || type === "L" || type === "K") {
|
|
1201
|
+
const data2 = await r.exact(size) ?? new Uint8Array(0);
|
|
1202
|
+
await r.skip((BLOCK - size % BLOCK) % BLOCK);
|
|
1203
|
+
if (type === "x") pax = { ...pax, ...parsePax(data2) };
|
|
1204
|
+
else if (type === "L") longName = cstring(data2);
|
|
1205
|
+
else if (type === "K") longLink = cstring(data2);
|
|
1206
|
+
continue;
|
|
1207
|
+
}
|
|
1208
|
+
if (pax.size !== void 0) size = Number(pax.size);
|
|
1209
|
+
name = pax.path ?? longName ?? name;
|
|
1210
|
+
linkname = pax.linkpath ?? longLink ?? linkname;
|
|
1211
|
+
pax = {};
|
|
1212
|
+
longName = longLink = void 0;
|
|
1213
|
+
if (!Number.isSafeInteger(size) || size < 0) throw invalidArchive("bad size");
|
|
1214
|
+
const kind = type === "0" || type === "\0" || type === "7" ? "file" : type === "5" ? "dir" : type === "2" ? "symlink" : type === "1" ? "link" : "other";
|
|
1215
|
+
const dataSize = kind === "file" || kind === "other" ? size : 0;
|
|
1216
|
+
let consumed = false;
|
|
1217
|
+
const data = {
|
|
1218
|
+
[Symbol.asyncIterator]: () => {
|
|
1219
|
+
consumed = true;
|
|
1220
|
+
return r.chunks(kind === "file" ? dataSize : 0);
|
|
1221
|
+
}
|
|
1222
|
+
};
|
|
1223
|
+
yield { name, type: kind, mode, size: kind === "file" ? size : 0, linkname, data };
|
|
1224
|
+
if (kind !== "file" || !consumed) await r.skip(dataSize);
|
|
1225
|
+
await r.skip((BLOCK - dataSize % BLOCK) % BLOCK);
|
|
1226
|
+
}
|
|
1227
|
+
}
|
|
1228
|
+
|
|
1229
|
+
// src/local.ts
|
|
1230
|
+
function load() {
|
|
1231
|
+
return Promise.all([
|
|
1232
|
+
import("node:fs"),
|
|
1233
|
+
import("node:fs/promises"),
|
|
1234
|
+
import("node:path"),
|
|
1235
|
+
import("node:zlib"),
|
|
1236
|
+
import("node:stream"),
|
|
1237
|
+
import("node:stream/promises"),
|
|
1238
|
+
import("node:child_process")
|
|
1239
|
+
]).then(
|
|
1240
|
+
// A namespace import of a CommonJS built-in (node:stream) types differently from `typeof import`.
|
|
1241
|
+
([fs, fsp, path, zlib, stream, sp, cp]) => ({ fs, fsp, path, zlib, stream, sp, cp })
|
|
1242
|
+
);
|
|
1243
|
+
}
|
|
1244
|
+
var mods;
|
|
1245
|
+
function node() {
|
|
1246
|
+
const m = mods ??= load().catch((err) => {
|
|
1247
|
+
mods = void 0;
|
|
1248
|
+
throw new InstaboxError("files.upload and files.download need Node.js (or Bun or Deno) file system access", {
|
|
1249
|
+
code: "unsupported",
|
|
1250
|
+
cause: err
|
|
1251
|
+
});
|
|
1252
|
+
});
|
|
1253
|
+
return m;
|
|
1254
|
+
}
|
|
1255
|
+
function localError(err, what) {
|
|
1256
|
+
if (err instanceof InstaboxError) return err;
|
|
1257
|
+
const code = err?.code;
|
|
1258
|
+
const msg = err?.message ?? String(err);
|
|
1259
|
+
if (code === "ENOENT")
|
|
1260
|
+
return new InstaboxError(`${what}: no such file or directory`, { code: "local_not_found", cause: err });
|
|
1261
|
+
return new InstaboxError(`${what}: ${msg}`, { code: "local_io_error", cause: err });
|
|
1262
|
+
}
|
|
1263
|
+
function run(n, file, args) {
|
|
1264
|
+
return new Promise((resolve) => {
|
|
1265
|
+
n.cp.execFile(
|
|
1266
|
+
file,
|
|
1267
|
+
args,
|
|
1268
|
+
{ encoding: "buffer", maxBuffer: 256 * 1024 * 1024 },
|
|
1269
|
+
(err, stdout) => resolve({ ok: !err, stdout })
|
|
1270
|
+
);
|
|
1271
|
+
});
|
|
1272
|
+
}
|
|
1273
|
+
async function listLocal(n, dir, opts = {}) {
|
|
1274
|
+
if (opts.git !== false) {
|
|
1275
|
+
const inside = await run(n, "git", ["-C", dir, "rev-parse", "--is-inside-work-tree"]);
|
|
1276
|
+
if (inside.ok && inside.stdout.toString().trim() === "true") {
|
|
1277
|
+
const args = opts.all ? ["-C", dir, "ls-files", "-co", "--exclude-standard", "-z"] : ["-C", dir, "ls-files", "-c", "-z"];
|
|
1278
|
+
const ls = await run(n, "git", args);
|
|
1279
|
+
if (!ls.ok) throw new InstaboxError(`git ls-files failed in ${dir}`, { code: "local_io_error" });
|
|
1280
|
+
return { names: ls.stdout.toString("utf8").split("\0").filter(Boolean), git: true };
|
|
1281
|
+
}
|
|
1282
|
+
}
|
|
1283
|
+
const names = [];
|
|
1284
|
+
const walk = async (rel) => {
|
|
1285
|
+
const abs = rel ? n.path.join(dir, rel) : dir;
|
|
1286
|
+
const ents = await n.fsp.readdir(abs, { withFileTypes: true });
|
|
1287
|
+
ents.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
|
|
1288
|
+
for (const e of ents) {
|
|
1289
|
+
const r = rel ? `${rel}/${e.name}` : e.name;
|
|
1290
|
+
names.push(r);
|
|
1291
|
+
if (e.isDirectory()) await walk(r);
|
|
1292
|
+
}
|
|
1293
|
+
};
|
|
1294
|
+
await walk("");
|
|
1295
|
+
return { names, git: false };
|
|
1296
|
+
}
|
|
1297
|
+
function packLocal(n, dir, names, counts) {
|
|
1298
|
+
async function* entries() {
|
|
1299
|
+
for (const rel of names) {
|
|
1300
|
+
const abs = n.path.join(dir, ...rel.split("/"));
|
|
1301
|
+
let st;
|
|
1302
|
+
try {
|
|
1303
|
+
st = await n.fsp.lstat(abs);
|
|
1304
|
+
} catch (err) {
|
|
1305
|
+
if (err.code === "ENOENT") continue;
|
|
1306
|
+
throw localError(err, abs);
|
|
1307
|
+
}
|
|
1308
|
+
const base = { name: rel, mode: st.mode & 4095, mtime: Math.floor(st.mtimeMs / 1e3) };
|
|
1309
|
+
if (st.isFile()) {
|
|
1310
|
+
counts.files++;
|
|
1311
|
+
yield {
|
|
1312
|
+
...base,
|
|
1313
|
+
type: "file",
|
|
1314
|
+
size: st.size,
|
|
1315
|
+
data: () => n.fs.createReadStream(abs, { highWaterMark: 256 * 1024 })
|
|
1316
|
+
};
|
|
1317
|
+
} else if (st.isDirectory()) yield { ...base, type: "dir" };
|
|
1318
|
+
else if (st.isSymbolicLink()) yield { ...base, type: "symlink", linkname: await n.fsp.readlink(abs) };
|
|
1319
|
+
}
|
|
1320
|
+
}
|
|
1321
|
+
const tar = n.stream.Readable.from(tarStream(entries()), { objectMode: false });
|
|
1322
|
+
const gz = n.zlib.createGzip();
|
|
1323
|
+
n.stream.pipeline(tar, gz, () => {
|
|
1324
|
+
});
|
|
1325
|
+
return gz;
|
|
1326
|
+
}
|
|
1327
|
+
function unsafe(name) {
|
|
1328
|
+
return new InstaboxError(`unsafe path ${JSON.stringify(name)} in the archive from the sandbox`, {
|
|
1329
|
+
code: "invalid_response"
|
|
1330
|
+
});
|
|
1331
|
+
}
|
|
1332
|
+
var RESERVED = /* @__PURE__ */ new Set([
|
|
1333
|
+
"CON",
|
|
1334
|
+
"PRN",
|
|
1335
|
+
"AUX",
|
|
1336
|
+
"NUL",
|
|
1337
|
+
"CONIN$",
|
|
1338
|
+
"CONOUT$",
|
|
1339
|
+
...["COM", "LPT"].flatMap((d) => [1, 2, 3, 4, 5, 6, 7, 8, 9, "\xB9", "\xB2", "\xB3"].map((i) => `${d}${i}`))
|
|
1340
|
+
]);
|
|
1341
|
+
var WINDOWS = globalThis.process?.platform === "win32";
|
|
1342
|
+
function components(name, windows = WINDOWS) {
|
|
1343
|
+
if (name.startsWith("/")) throw unsafe(name);
|
|
1344
|
+
const parts = [];
|
|
1345
|
+
for (const p of name.split("/")) {
|
|
1346
|
+
if (p === "" || p === ".") continue;
|
|
1347
|
+
if (p === ".." || p.includes("\\") || p.includes("\0")) throw unsafe(name);
|
|
1348
|
+
if (windows && (p.includes(":") || p.endsWith(".") || p.endsWith(" ") || RESERVED.has(p.split(".")[0].replace(/ +$/, "").toUpperCase()))) {
|
|
1349
|
+
throw unsafe(name);
|
|
1350
|
+
}
|
|
1351
|
+
parts.push(p);
|
|
1352
|
+
}
|
|
1353
|
+
return parts;
|
|
1354
|
+
}
|
|
1355
|
+
async function unpackLocal(n, src, dest, windows = WINDOWS) {
|
|
1356
|
+
await n.fsp.mkdir(dest, { recursive: true });
|
|
1357
|
+
const root = await n.fsp.realpath(dest);
|
|
1358
|
+
const gunzip = n.zlib.createGunzip();
|
|
1359
|
+
n.stream.pipeline(n.stream.Readable.from(src, { objectMode: false }), gunzip, () => {
|
|
1360
|
+
});
|
|
1361
|
+
const dirModes = /* @__PURE__ */ new Map();
|
|
1362
|
+
let files = 0;
|
|
1363
|
+
const writable = async (abs, st) => {
|
|
1364
|
+
const mode = st.mode & 4095;
|
|
1365
|
+
if ((mode & 192) === 192 || dirModes.has(abs)) return;
|
|
1366
|
+
dirModes.set(abs, mode);
|
|
1367
|
+
await n.fsp.chmod(abs, mode | 192);
|
|
1368
|
+
};
|
|
1369
|
+
await writable(root, await n.fsp.stat(root));
|
|
1370
|
+
const ensureDir = async (parts, name) => {
|
|
1371
|
+
let cur = root;
|
|
1372
|
+
for (const p of parts) {
|
|
1373
|
+
cur = n.path.join(cur, p);
|
|
1374
|
+
let st;
|
|
1375
|
+
try {
|
|
1376
|
+
st = await n.fsp.lstat(cur);
|
|
1377
|
+
} catch (err) {
|
|
1378
|
+
if (err.code !== "ENOENT") throw err;
|
|
1379
|
+
}
|
|
1380
|
+
if (!st) await n.fsp.mkdir(cur, { mode: 493 });
|
|
1381
|
+
else if (!st.isDirectory()) throw unsafe(name);
|
|
1382
|
+
else await writable(cur, st);
|
|
1383
|
+
}
|
|
1384
|
+
return cur;
|
|
1385
|
+
};
|
|
1386
|
+
const clear = async (abs, name) => {
|
|
1387
|
+
let st;
|
|
1388
|
+
try {
|
|
1389
|
+
st = await n.fsp.lstat(abs);
|
|
1390
|
+
} catch {
|
|
1391
|
+
return;
|
|
1392
|
+
}
|
|
1393
|
+
if (st.isDirectory()) {
|
|
1394
|
+
throw new InstaboxError(`${name} is a directory locally; the archive has a file there`, {
|
|
1395
|
+
code: "local_io_error"
|
|
1396
|
+
});
|
|
1397
|
+
}
|
|
1398
|
+
await n.fsp.unlink(abs);
|
|
1399
|
+
};
|
|
1400
|
+
let ok = false;
|
|
1401
|
+
try {
|
|
1402
|
+
for await (const e of untarStream(gunzip)) {
|
|
1403
|
+
const parts = components(e.name, windows);
|
|
1404
|
+
if (parts.length === 0) {
|
|
1405
|
+
for await (const _ of e.data) void _;
|
|
1406
|
+
continue;
|
|
1407
|
+
}
|
|
1408
|
+
const parent = await ensureDir(parts.slice(0, -1), e.name);
|
|
1409
|
+
const abs = n.path.join(parent, parts[parts.length - 1]);
|
|
1410
|
+
if (e.type === "dir") {
|
|
1411
|
+
await ensureDir(parts, e.name);
|
|
1412
|
+
dirModes.set(abs, e.mode);
|
|
1413
|
+
} else if (e.type === "file") {
|
|
1414
|
+
await clear(abs, e.name);
|
|
1415
|
+
await n.sp.pipeline(
|
|
1416
|
+
n.stream.Readable.from(e.data, { objectMode: false }),
|
|
1417
|
+
n.fs.createWriteStream(abs, { flags: "wx", mode: e.mode | 128 })
|
|
1418
|
+
);
|
|
1419
|
+
await n.fsp.chmod(abs, e.mode);
|
|
1420
|
+
files++;
|
|
1421
|
+
} else if (e.type === "symlink") {
|
|
1422
|
+
await clear(abs, e.name);
|
|
1423
|
+
await n.fsp.symlink(e.linkname, abs);
|
|
1424
|
+
} else if (e.type === "link") {
|
|
1425
|
+
const tparts = components(e.linkname, windows);
|
|
1426
|
+
const target = n.path.join(await ensureDir(tparts.slice(0, -1), e.linkname), tparts[tparts.length - 1] ?? "");
|
|
1427
|
+
const st = await n.fsp.lstat(target).catch(() => void 0);
|
|
1428
|
+
if (!st?.isFile()) throw unsafe(e.linkname);
|
|
1429
|
+
await clear(abs, e.name);
|
|
1430
|
+
await n.fsp.copyFile(target, abs);
|
|
1431
|
+
files++;
|
|
1432
|
+
}
|
|
1433
|
+
}
|
|
1434
|
+
ok = true;
|
|
1435
|
+
} finally {
|
|
1436
|
+
const depth = (p) => p.split(n.path.sep).length;
|
|
1437
|
+
for (const [abs, mode] of [...dirModes].sort((a, b) => depth(b[0]) - depth(a[0]))) {
|
|
1438
|
+
await n.fsp.chmod(abs, mode).catch((err) => {
|
|
1439
|
+
if (ok) throw err;
|
|
1440
|
+
});
|
|
1441
|
+
}
|
|
1442
|
+
}
|
|
1443
|
+
return files;
|
|
1444
|
+
}
|
|
1445
|
+
|
|
876
1446
|
// src/files.ts
|
|
877
1447
|
var MAX_FILE_BYTES = 10 * 1024 * 1024;
|
|
1448
|
+
var MAX_UPLOAD_BYTES = 5 * 1024 * 1024 * 1024;
|
|
878
1449
|
var TRANSFER_TIMEOUT_MS = 3e5;
|
|
1450
|
+
var TRANSFER_MAX_MS = 72e5 + 12e4;
|
|
1451
|
+
var TRANSFER_IDLE_MS = 12e4;
|
|
1452
|
+
var TRANSFER_EXEC_MS = 6e5;
|
|
879
1453
|
var WRITE_CHUNK_B64 = 48 * 1024;
|
|
880
1454
|
var READ_CHUNK_BYTES = 512 * 1024;
|
|
1455
|
+
var PROBE_PATH = "instabox-sdk-route-probe";
|
|
881
1456
|
var Files = class {
|
|
882
1457
|
/** @internal */
|
|
883
1458
|
constructor(commands, http, sandboxId) {
|
|
@@ -891,22 +1466,45 @@ var Files = class {
|
|
|
891
1466
|
home;
|
|
892
1467
|
/** False once a server answered that it has no file routes. */
|
|
893
1468
|
routes = true;
|
|
1469
|
+
/** True once a server answered on a file route, so a stream need not probe for it. */
|
|
1470
|
+
routesSeen = false;
|
|
1471
|
+
get filesPath() {
|
|
1472
|
+
return `/v1/machines/${encodeURIComponent(this.sandboxId ?? "")}/files`;
|
|
1473
|
+
}
|
|
894
1474
|
async read(path, opts = {}) {
|
|
895
1475
|
const limit = opts.maxBytes ?? MAX_FILE_BYTES;
|
|
896
|
-
|
|
897
|
-
const
|
|
1476
|
+
if (!(limit >= 0)) throw new InstaboxError("maxBytes must be a number, at least 0", { code: "bad_request" });
|
|
1477
|
+
const res = await this.openRoute(path);
|
|
1478
|
+
const bytes = res ? await this.readRoute(res, path, limit) : await this.readExec(path, limit);
|
|
898
1479
|
return opts.format === "bytes" ? bytes : decodeUtf8(bytes);
|
|
899
1480
|
}
|
|
900
|
-
/**
|
|
901
|
-
|
|
1481
|
+
/**
|
|
1482
|
+
* Opens a file for reading as a stream, with no size cap: the bytes arrive as the server sends them,
|
|
1483
|
+
* so a file of any size reads in bounded memory. Errors before the first byte (`not_found`, a
|
|
1484
|
+
* directory) reject the promise; a stream cut short errors with `file_changed`. Read it with
|
|
1485
|
+
* `for await`, `getReader()`, or in Node `Readable.fromWeb(stream)` and `pipeline`. On a server
|
|
1486
|
+
* without the file routes the file is read over exec first (at most 10 MiB).
|
|
1487
|
+
*/
|
|
1488
|
+
async readStream(path, opts = {}) {
|
|
1489
|
+
const res = await this.openRoute(path, opts.signal);
|
|
1490
|
+
if (!res) return iterable(oneChunk(await this.readExec(path, MAX_FILE_BYTES)));
|
|
1491
|
+
return iterable(this.countedBody(res, path, opts.signal));
|
|
1492
|
+
}
|
|
1493
|
+
/**
|
|
1494
|
+
* `GET .../files/content` of `path` (or of `abs`, already absolute); undefined when the server has
|
|
1495
|
+
* no such route. `not_found` and `not_a_file` become `not_found`: a directory is not a file either.
|
|
1496
|
+
*/
|
|
1497
|
+
async openRoute(path, signal, abs) {
|
|
902
1498
|
if (!this.http || !this.sandboxId || !this.routes) return void 0;
|
|
903
|
-
|
|
904
|
-
let res;
|
|
1499
|
+
abs ??= await this.absolute(path);
|
|
905
1500
|
try {
|
|
906
|
-
res = await this.http.send("GET",
|
|
1501
|
+
const res = await this.http.send("GET", `${this.filesPath}/content`, {
|
|
907
1502
|
query: { path: abs },
|
|
908
|
-
timeoutMs: TRANSFER_TIMEOUT_MS
|
|
1503
|
+
timeoutMs: TRANSFER_TIMEOUT_MS,
|
|
1504
|
+
signal
|
|
909
1505
|
});
|
|
1506
|
+
this.routesSeen = true;
|
|
1507
|
+
return res;
|
|
910
1508
|
} catch (err) {
|
|
911
1509
|
if (routeMissing(err)) {
|
|
912
1510
|
this.routes = false;
|
|
@@ -922,19 +1520,72 @@ var Files = class {
|
|
|
922
1520
|
}
|
|
923
1521
|
throw err;
|
|
924
1522
|
}
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
1523
|
+
}
|
|
1524
|
+
/** Reads a whole response body of `path`, at most `limit` bytes. */
|
|
1525
|
+
async readRoute(res, path, limit) {
|
|
1526
|
+
try {
|
|
1527
|
+
const declared = Number(res.headers.get("Content-Length") ?? NaN);
|
|
1528
|
+
if (Number.isSafeInteger(declared) && declared > limit) {
|
|
1529
|
+
void res.body?.cancel().catch(() => {
|
|
1530
|
+
});
|
|
1531
|
+
throw new InstaboxError(`${path} is larger than the ${limit}-byte limit of files.read`, {
|
|
1532
|
+
code: "file_too_large"
|
|
1533
|
+
});
|
|
1534
|
+
}
|
|
1535
|
+
const bytes = await readBody(res, limit, path);
|
|
1536
|
+
if (Number.isSafeInteger(declared) && bytes.length !== declared) {
|
|
1537
|
+
throw new InstaboxError(`got ${bytes.length} of ${declared} bytes of ${path}`, { code: "file_changed" });
|
|
1538
|
+
}
|
|
1539
|
+
return bytes;
|
|
1540
|
+
} finally {
|
|
1541
|
+
this.http?.release(res);
|
|
936
1542
|
}
|
|
937
|
-
|
|
1543
|
+
}
|
|
1544
|
+
/** A response body as a stream that errors with `file_changed` when it ends short of Content-Length. */
|
|
1545
|
+
countedBody(res, path, signal) {
|
|
1546
|
+
const http = this.http;
|
|
1547
|
+
const declared = Number(res.headers.get("Content-Length") ?? NaN);
|
|
1548
|
+
const reader = res.body?.getReader();
|
|
1549
|
+
let n = 0;
|
|
1550
|
+
return new ReadableStream(
|
|
1551
|
+
{
|
|
1552
|
+
async pull(c) {
|
|
1553
|
+
if (!reader) {
|
|
1554
|
+
http.release(res);
|
|
1555
|
+
return c.close();
|
|
1556
|
+
}
|
|
1557
|
+
let r;
|
|
1558
|
+
try {
|
|
1559
|
+
r = await reader.read();
|
|
1560
|
+
} catch (err) {
|
|
1561
|
+
http.release(res);
|
|
1562
|
+
if (signal?.aborted) return c.error(new InstaboxError(`reading ${path} was aborted`, { code: "aborted" }));
|
|
1563
|
+
const msg = err?.message ?? String(err);
|
|
1564
|
+
return c.error(
|
|
1565
|
+
new InstaboxError(`reading ${path} stopped after ${n} bytes: ${msg}`, {
|
|
1566
|
+
code: "file_changed",
|
|
1567
|
+
retryable: true,
|
|
1568
|
+
cause: err
|
|
1569
|
+
})
|
|
1570
|
+
);
|
|
1571
|
+
}
|
|
1572
|
+
if (r.done) {
|
|
1573
|
+
http.release(res);
|
|
1574
|
+
if (Number.isSafeInteger(declared) && n !== declared) {
|
|
1575
|
+
return c.error(new InstaboxError(`got ${n} of ${declared} bytes of ${path}`, { code: "file_changed" }));
|
|
1576
|
+
}
|
|
1577
|
+
return c.close();
|
|
1578
|
+
}
|
|
1579
|
+
n += r.value.length;
|
|
1580
|
+
c.enqueue(r.value);
|
|
1581
|
+
},
|
|
1582
|
+
cancel(reason) {
|
|
1583
|
+
http.release(res);
|
|
1584
|
+
return reader?.cancel(reason);
|
|
1585
|
+
}
|
|
1586
|
+
},
|
|
1587
|
+
{ highWaterMark: 0 }
|
|
1588
|
+
);
|
|
938
1589
|
}
|
|
939
1590
|
async readExec(path, limit) {
|
|
940
1591
|
const p = arg(path);
|
|
@@ -967,57 +1618,201 @@ var Files = class {
|
|
|
967
1618
|
return bytes;
|
|
968
1619
|
}
|
|
969
1620
|
/**
|
|
970
|
-
* Writes a file, creating parent directories. Replaces the file atomically (temp file + rename)
|
|
971
|
-
* Throws `is_a_directory` when `path` is a directory.
|
|
1621
|
+
* Writes a file, creating parent directories. Replaces the file atomically (temp file + rename), so
|
|
1622
|
+
* a failed or aborted write leaves the old file. Throws `is_a_directory` when `path` is a directory.
|
|
1623
|
+
*
|
|
1624
|
+
* `data` is a string, bytes, or a stream (a Node `Readable`, a web `ReadableStream`, an
|
|
1625
|
+
* `AsyncIterable` of chunks): a stream is sent as it is read, in bounded memory, up to the server's
|
|
1626
|
+
* 5 GiB. The size and SHA-256 the server reports are checked against what was sent
|
|
1627
|
+
* (`transfer_mismatch` when they differ). On a server without the file routes, writes go over exec
|
|
1628
|
+
* and are capped at 10 MiB (`file_too_large`).
|
|
972
1629
|
*/
|
|
973
|
-
async write(path, data) {
|
|
974
|
-
const bytes =
|
|
975
|
-
if (bytes
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
1630
|
+
async write(path, data, opts = {}) {
|
|
1631
|
+
const bytes = asBytes(data);
|
|
1632
|
+
if (bytes) {
|
|
1633
|
+
if (await this.writeRoute(path, bytes, opts.signal)) return { path };
|
|
1634
|
+
if (bytes.length > MAX_FILE_BYTES) throw tooLargeForExec();
|
|
1635
|
+
await this.writeExec(path, bytes);
|
|
1636
|
+
return { path };
|
|
1637
|
+
}
|
|
1638
|
+
const src = asIterable(data);
|
|
1639
|
+
if (await this.routesAvailable(opts.signal)) {
|
|
1640
|
+
if (await this.writeRoute(path, src, opts.signal)) return { path };
|
|
1641
|
+
throw noRoutes();
|
|
979
1642
|
}
|
|
980
|
-
|
|
981
|
-
await this.writeExec(path, bytes);
|
|
1643
|
+
await this.writeExec(path, await collect(src, MAX_FILE_BYTES));
|
|
982
1644
|
return { path };
|
|
983
1645
|
}
|
|
984
1646
|
/**
|
|
985
1647
|
* Writes over `PUT .../files?parents=true`, which writes a temp file beside the target and renames
|
|
986
1648
|
* it into place once every byte arrived. False when the server has no such route.
|
|
987
1649
|
*/
|
|
988
|
-
async
|
|
1650
|
+
async writeRoute(path, body, signal) {
|
|
989
1651
|
if (!this.http || !this.sandboxId || !this.routes) return false;
|
|
990
1652
|
const abs = await this.absolute(path);
|
|
991
|
-
let res;
|
|
992
1653
|
try {
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
1654
|
+
return await this.put(abs, body, { parents: "true" }, signal) !== void 0;
|
|
1655
|
+
} catch (err) {
|
|
1656
|
+
if (err instanceof InstaboxError && err.code === "not_a_file") {
|
|
1657
|
+
const dir = await this.commands.exec(`test -d ${arg(path)}`).catch(() => void 0);
|
|
1658
|
+
if (dir?.exitCode === 0) {
|
|
1659
|
+
throw new InstaboxError(`is a directory: ${path}`, { status: 409, code: "is_a_directory", cause: err });
|
|
1660
|
+
}
|
|
1661
|
+
}
|
|
1662
|
+
throw err;
|
|
1663
|
+
}
|
|
1664
|
+
}
|
|
1665
|
+
/**
|
|
1666
|
+
* True when the server has the file routes. A stream can be sent only once, so before the first one
|
|
1667
|
+
* the route is probed with a relative path, which the server refuses (400) before touching the
|
|
1668
|
+
* sandbox; a server without the route answers 404 or 405.
|
|
1669
|
+
*/
|
|
1670
|
+
async routesAvailable(signal) {
|
|
1671
|
+
if (!this.http || !this.sandboxId || !this.routes) return false;
|
|
1672
|
+
if (this.routesSeen) return true;
|
|
1673
|
+
try {
|
|
1674
|
+
await this.http.request("PUT", this.filesPath, {
|
|
1675
|
+
query: { path: PROBE_PATH },
|
|
1676
|
+
rawBody: new Uint8Array(0),
|
|
996
1677
|
idempotent: false,
|
|
997
1678
|
retry: true,
|
|
998
|
-
|
|
1679
|
+
signal
|
|
999
1680
|
});
|
|
1000
1681
|
} catch (err) {
|
|
1001
1682
|
if (routeMissing(err)) {
|
|
1002
1683
|
this.routes = false;
|
|
1003
1684
|
return false;
|
|
1004
1685
|
}
|
|
1005
|
-
if (err instanceof InstaboxError
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1686
|
+
if (!(err instanceof InstaboxError) || err.status !== 400) throw err;
|
|
1687
|
+
}
|
|
1688
|
+
this.routesSeen = true;
|
|
1689
|
+
return true;
|
|
1690
|
+
}
|
|
1691
|
+
/**
|
|
1692
|
+
* `PUT .../files` of `body` to the absolute path `abs`, checking the size and SHA-256 the server
|
|
1693
|
+
* reports. Bytes are retried on 502-504 (the server replaces the file atomically, so a repeat writes
|
|
1694
|
+
* the same bytes); a stream is sent once, as it is read, and given up when it moves nothing for
|
|
1695
|
+
* 2 minutes. Undefined when the server has no such route.
|
|
1696
|
+
*/
|
|
1697
|
+
async put(abs, body, query, signal) {
|
|
1698
|
+
if (!this.http || !this.sandboxId || !this.routes) return void 0;
|
|
1699
|
+
let res;
|
|
1700
|
+
let sent;
|
|
1701
|
+
let want;
|
|
1702
|
+
if (body instanceof Uint8Array) {
|
|
1703
|
+
try {
|
|
1704
|
+
res = await this.http.request("PUT", this.filesPath, {
|
|
1705
|
+
query: { path: abs, ...query },
|
|
1706
|
+
rawBody: body,
|
|
1707
|
+
idempotent: false,
|
|
1708
|
+
retry: true,
|
|
1709
|
+
timeoutMs: bufferedTimeout(body.length),
|
|
1710
|
+
signal
|
|
1711
|
+
});
|
|
1712
|
+
} catch (err) {
|
|
1713
|
+
if (routeMissing(err)) {
|
|
1714
|
+
this.routes = false;
|
|
1715
|
+
return void 0;
|
|
1009
1716
|
}
|
|
1717
|
+
throw err;
|
|
1010
1718
|
}
|
|
1011
|
-
|
|
1719
|
+
sent = body.length;
|
|
1720
|
+
want = await sha256Hex(body);
|
|
1721
|
+
} else {
|
|
1722
|
+
const up = await this.putStream(abs, body, query, signal);
|
|
1723
|
+
if (!up) return void 0;
|
|
1724
|
+
({ res, sent, want } = up);
|
|
1012
1725
|
}
|
|
1013
|
-
|
|
1014
|
-
if (res?.size !==
|
|
1726
|
+
this.routesSeen = true;
|
|
1727
|
+
if (res?.size !== sent || want !== void 0 && res.sha256 !== want) {
|
|
1015
1728
|
throw new InstaboxError(
|
|
1016
|
-
`the sandbox received ${res?.size} bytes with sha256 ${res?.sha256}; sent ${
|
|
1729
|
+
`the sandbox received ${res?.size} bytes with sha256 ${res?.sha256}; sent ${sent} with ${want}`,
|
|
1017
1730
|
{ code: "transfer_mismatch" }
|
|
1018
1731
|
);
|
|
1019
1732
|
}
|
|
1020
|
-
return
|
|
1733
|
+
return { size: sent };
|
|
1734
|
+
}
|
|
1735
|
+
async putStream(abs, src, query, signal) {
|
|
1736
|
+
const hash = await sha256Stream();
|
|
1737
|
+
const ctrl = new AbortController();
|
|
1738
|
+
let idle;
|
|
1739
|
+
let idleFired = false;
|
|
1740
|
+
const touch = () => {
|
|
1741
|
+
clearTimeout(idle);
|
|
1742
|
+
idle = setTimeout(() => {
|
|
1743
|
+
idleFired = true;
|
|
1744
|
+
ctrl.abort();
|
|
1745
|
+
}, TRANSFER_IDLE_MS);
|
|
1746
|
+
};
|
|
1747
|
+
const onAbort = () => ctrl.abort();
|
|
1748
|
+
if (signal?.aborted) ctrl.abort();
|
|
1749
|
+
else signal?.addEventListener("abort", onAbort, { once: true });
|
|
1750
|
+
const it = src[Symbol.asyncIterator]();
|
|
1751
|
+
let sent = 0;
|
|
1752
|
+
let srcErr;
|
|
1753
|
+
const stream = new ReadableStream(
|
|
1754
|
+
{
|
|
1755
|
+
async pull(c) {
|
|
1756
|
+
touch();
|
|
1757
|
+
let r;
|
|
1758
|
+
try {
|
|
1759
|
+
r = await it.next();
|
|
1760
|
+
if (!r.done) {
|
|
1761
|
+
const b = chunkBytes(r.value);
|
|
1762
|
+
sent += b.length;
|
|
1763
|
+
if (sent > MAX_UPLOAD_BYTES) {
|
|
1764
|
+
throw new InstaboxError(`data is larger than the ${MAX_UPLOAD_BYTES}-byte limit of files.write`, {
|
|
1765
|
+
status: 413,
|
|
1766
|
+
code: "too_large"
|
|
1767
|
+
});
|
|
1768
|
+
}
|
|
1769
|
+
hash?.update(b);
|
|
1770
|
+
if (b.length) c.enqueue(b);
|
|
1771
|
+
return;
|
|
1772
|
+
}
|
|
1773
|
+
} catch (err) {
|
|
1774
|
+
clearTimeout(idle);
|
|
1775
|
+
srcErr = sourceError(err);
|
|
1776
|
+
throw srcErr;
|
|
1777
|
+
}
|
|
1778
|
+
clearTimeout(idle);
|
|
1779
|
+
c.close();
|
|
1780
|
+
},
|
|
1781
|
+
async cancel() {
|
|
1782
|
+
clearTimeout(idle);
|
|
1783
|
+
await it.return?.();
|
|
1784
|
+
}
|
|
1785
|
+
},
|
|
1786
|
+
{ highWaterMark: 0 }
|
|
1787
|
+
);
|
|
1788
|
+
try {
|
|
1789
|
+
const res = await this.http.request("PUT", this.filesPath, {
|
|
1790
|
+
query: { path: abs, ...query },
|
|
1791
|
+
streamBody: stream,
|
|
1792
|
+
idempotent: false,
|
|
1793
|
+
timeoutMs: TRANSFER_MAX_MS,
|
|
1794
|
+
signal: ctrl.signal
|
|
1795
|
+
});
|
|
1796
|
+
return { res, sent, want: hash?.digest("hex") };
|
|
1797
|
+
} catch (err) {
|
|
1798
|
+
if (srcErr) throw srcErr;
|
|
1799
|
+
if (idleFired) {
|
|
1800
|
+
throw new InstaboxTimeoutError(`the upload to ${abs} moved nothing for ${TRANSFER_IDLE_MS / 1e3} s`, {
|
|
1801
|
+
code: "request_timeout",
|
|
1802
|
+
cause: err
|
|
1803
|
+
});
|
|
1804
|
+
}
|
|
1805
|
+
if (routeMissing(err)) {
|
|
1806
|
+
this.routes = false;
|
|
1807
|
+
return void 0;
|
|
1808
|
+
}
|
|
1809
|
+
throw err;
|
|
1810
|
+
} finally {
|
|
1811
|
+
clearTimeout(idle);
|
|
1812
|
+
signal?.removeEventListener("abort", onAbort);
|
|
1813
|
+
void it.return?.()?.catch?.(() => {
|
|
1814
|
+
});
|
|
1815
|
+
}
|
|
1021
1816
|
}
|
|
1022
1817
|
async writeExec(path, bytes) {
|
|
1023
1818
|
const p = arg(path);
|
|
@@ -1042,6 +1837,172 @@ var Files = class {
|
|
|
1042
1837
|
throw err;
|
|
1043
1838
|
}
|
|
1044
1839
|
}
|
|
1840
|
+
/**
|
|
1841
|
+
* Puts `src` at the absolute temporary path `abs` (mode 0600): over the file route, or in base64
|
|
1842
|
+
* chunks over exec (`instabox push`'s fallback) on a server without it.
|
|
1843
|
+
*/
|
|
1844
|
+
async putTemp(abs, src, signal) {
|
|
1845
|
+
const replayable = src instanceof Uint8Array;
|
|
1846
|
+
if (replayable || await this.routesAvailable(signal)) {
|
|
1847
|
+
if (await this.put(abs, src, { mode: "0600" }, signal)) return;
|
|
1848
|
+
if (!replayable) throw noRoutes();
|
|
1849
|
+
}
|
|
1850
|
+
let first = true;
|
|
1851
|
+
for await (const chunk of rechunk(replayable ? [src] : src, EXEC_CHUNK_BYTES)) {
|
|
1852
|
+
if (signal?.aborted) throw new InstaboxError("the transfer was aborted", { code: "aborted" });
|
|
1853
|
+
await this.transferExec(PUSH_CHUNK_SCRIPT, { IB_TMP: abs, IB_FIRST: first ? "1" : "0" }, "", signal, {
|
|
1854
|
+
stdin: bytesToBase64(chunk)
|
|
1855
|
+
});
|
|
1856
|
+
first = false;
|
|
1857
|
+
}
|
|
1858
|
+
if (first) await this.transferExec(PUSH_CHUNK_SCRIPT, { IB_TMP: abs, IB_FIRST: "1" }, "", signal, { stdin: "" });
|
|
1859
|
+
}
|
|
1860
|
+
/**
|
|
1861
|
+
* Runs a transfer script and returns its stdout after `mark`. A non-zero exit throws `transfer_failed`
|
|
1862
|
+
* (`permission_denied`, status 403, when the sandbox refused access), as the CLI reports it.
|
|
1863
|
+
*/
|
|
1864
|
+
async transferExec(cmd, envs, mark, signal, extra = {}) {
|
|
1865
|
+
const r = await this.commands.exec(cmd, { envs, timeoutMs: TRANSFER_EXEC_MS, signal, stdin: extra.stdin });
|
|
1866
|
+
if (r.timedOut) {
|
|
1867
|
+
throw new InstaboxTimeoutError(`the transfer timed out after ${TRANSFER_EXEC_MS / 1e3} s in the sandbox`, {
|
|
1868
|
+
code: "request_timeout"
|
|
1869
|
+
});
|
|
1870
|
+
}
|
|
1871
|
+
if (r.exitCode !== 0) {
|
|
1872
|
+
const msg = r.stderr.trim() || `exit status ${r.exitCode}`;
|
|
1873
|
+
if (/Permission denied|Operation not permitted/.test(msg)) {
|
|
1874
|
+
throw new InstaboxError(`in the sandbox: ${msg}`, { status: 403, code: "permission_denied" });
|
|
1875
|
+
}
|
|
1876
|
+
throw new InstaboxError(`in the sandbox: ${msg}`, { code: "transfer_failed" });
|
|
1877
|
+
}
|
|
1878
|
+
if (!mark) return "";
|
|
1879
|
+
const i = r.stdout.indexOf(mark);
|
|
1880
|
+
if (i < 0 || r.truncated)
|
|
1881
|
+
throw new InstaboxError("unexpected output from the sandbox", { code: "invalid_response" });
|
|
1882
|
+
return r.stdout.slice(i + mark.length);
|
|
1883
|
+
}
|
|
1884
|
+
/**
|
|
1885
|
+
* Uploads a local directory's contents into `remoteDir` in one call, as one gzipped tar, the way
|
|
1886
|
+
* `instabox push` does: streamed over `PUT .../files` to a temporary file, then unpacked in the
|
|
1887
|
+
* sandbox with `tar`. `remoteDir` and its parents are created; existing files there are replaced,
|
|
1888
|
+
* others kept. In a git work tree only what git tracks is uploaded (pass `all: true` to add
|
|
1889
|
+
* untracked files git does not ignore, `git: false` to upload everything). Symlinks are uploaded as
|
|
1890
|
+
* symlinks, never followed; sockets, FIFOs and devices are skipped. Node.js (or Bun, Deno) only.
|
|
1891
|
+
*/
|
|
1892
|
+
async upload(localDir, remoteDir, opts = {}) {
|
|
1893
|
+
const n = await node();
|
|
1894
|
+
const st = await n.fsp.stat(localDir).catch((err) => {
|
|
1895
|
+
throw localError(err, localDir);
|
|
1896
|
+
});
|
|
1897
|
+
if (!st.isDirectory()) {
|
|
1898
|
+
throw new InstaboxError(`${localDir} is not a directory; write a single file with files.write`, {
|
|
1899
|
+
code: "not_a_directory"
|
|
1900
|
+
});
|
|
1901
|
+
}
|
|
1902
|
+
const { names } = await listLocal(n, localDir, opts).catch((err) => {
|
|
1903
|
+
throw localError(err, localDir);
|
|
1904
|
+
});
|
|
1905
|
+
const counts = { files: 0 };
|
|
1906
|
+
let bytes = 0;
|
|
1907
|
+
const packed = packLocal(n, localDir, names, counts);
|
|
1908
|
+
async function* counted() {
|
|
1909
|
+
try {
|
|
1910
|
+
for await (const chunk of packed) {
|
|
1911
|
+
bytes += chunk.length;
|
|
1912
|
+
yield chunk;
|
|
1913
|
+
}
|
|
1914
|
+
} catch (err) {
|
|
1915
|
+
throw localError(err, localDir);
|
|
1916
|
+
}
|
|
1917
|
+
}
|
|
1918
|
+
const tmp = TRANSFER_TMP_PREFIX + randomHex();
|
|
1919
|
+
try {
|
|
1920
|
+
await this.putTemp(tmp, counted(), opts.signal);
|
|
1921
|
+
const out = await this.transferExec(
|
|
1922
|
+
PUSH_FINISH_SCRIPT,
|
|
1923
|
+
{ IB_TMP: tmp, IB_DEST: remoteDir },
|
|
1924
|
+
PUSH_MARK,
|
|
1925
|
+
opts.signal
|
|
1926
|
+
);
|
|
1927
|
+
const f = out.split("\0");
|
|
1928
|
+
if (f[0] !== "ok" || !f[1])
|
|
1929
|
+
throw new InstaboxError("unexpected output from the sandbox", { code: "invalid_response" });
|
|
1930
|
+
return { path: f[1], files: counts.files, bytes };
|
|
1931
|
+
} catch (err) {
|
|
1932
|
+
await this.commands.exec(`rm -f -- ${shellQuote(tmp)}`).catch(() => {
|
|
1933
|
+
});
|
|
1934
|
+
throw err;
|
|
1935
|
+
}
|
|
1936
|
+
}
|
|
1937
|
+
/**
|
|
1938
|
+
* Downloads a sandbox directory into `localDir` in one call, as one gzipped tar, the way
|
|
1939
|
+
* `instabox pull` packs it: `tar` in the sandbox (as root when sudo allows, as the file routes read),
|
|
1940
|
+
* streamed back over `GET .../files/content` and unpacked as it arrives. `localDir` and its parents
|
|
1941
|
+
* are created; existing files are replaced, others kept. Everything under `remoteDir` comes, dot
|
|
1942
|
+
* files and empty directories included; symlinks arrive as symlinks. No entry can write outside
|
|
1943
|
+
* `localDir`. Node.js (or Bun, Deno) only.
|
|
1944
|
+
*/
|
|
1945
|
+
async download(remoteDir, localDir, opts = {}) {
|
|
1946
|
+
const n = await node();
|
|
1947
|
+
const tmp = TRANSFER_TMP_PREFIX + randomHex();
|
|
1948
|
+
const envs = { IB_PATH: remoteDir };
|
|
1949
|
+
const f = (await this.transferExec(pullStartCmd(tmp), envs, PULL_MARK, opts.signal)).split("\0");
|
|
1950
|
+
if (f[0] === "missing") {
|
|
1951
|
+
throw new InstaboxError(`directory not found: ${remoteDir}`, { status: 404, code: "not_found" });
|
|
1952
|
+
}
|
|
1953
|
+
if (f[0] === "not_a_dir") {
|
|
1954
|
+
throw new InstaboxError(`${f[1]} is not a directory; read a single file with files.read or files.readStream`, {
|
|
1955
|
+
code: "not_a_directory"
|
|
1956
|
+
});
|
|
1957
|
+
}
|
|
1958
|
+
const size = Number(f[2]);
|
|
1959
|
+
if (f[0] !== "dir" || !f[1] || !Number.isSafeInteger(size) || size < 0) {
|
|
1960
|
+
throw new InstaboxError("unexpected output from the sandbox", { code: "invalid_response" });
|
|
1961
|
+
}
|
|
1962
|
+
try {
|
|
1963
|
+
let bytes = 0;
|
|
1964
|
+
const src = this.fetchTemp(tmp, size, envs, opts.signal);
|
|
1965
|
+
async function* counted() {
|
|
1966
|
+
for await (const chunk of src) {
|
|
1967
|
+
bytes += chunk.length;
|
|
1968
|
+
yield chunk;
|
|
1969
|
+
}
|
|
1970
|
+
}
|
|
1971
|
+
const files = await unpackLocal(n, counted(), localDir).catch((err) => {
|
|
1972
|
+
throw localError(err, localDir);
|
|
1973
|
+
});
|
|
1974
|
+
if (bytes !== size) {
|
|
1975
|
+
throw new InstaboxError(`got ${bytes} of ${size} bytes of the archive`, { code: "file_changed" });
|
|
1976
|
+
}
|
|
1977
|
+
return { path: localDir, remotePath: f[1], files, bytes };
|
|
1978
|
+
} finally {
|
|
1979
|
+
await this.commands.exec(pullRemoveCmd(tmp), { envs }).catch(() => {
|
|
1980
|
+
});
|
|
1981
|
+
}
|
|
1982
|
+
}
|
|
1983
|
+
/** The temporary archive's bytes: over the file route, or in base64 chunks over exec without it. */
|
|
1984
|
+
async *fetchTemp(tmp, size, envs, signal) {
|
|
1985
|
+
const res = await this.openRoute(tmp, signal, tmp);
|
|
1986
|
+
if (res) {
|
|
1987
|
+
yield* iterable(this.countedBody(res, tmp, signal));
|
|
1988
|
+
return;
|
|
1989
|
+
}
|
|
1990
|
+
for (let off = 0; off < size; off += EXEC_CHUNK_BYTES) {
|
|
1991
|
+
const want = Math.min(EXEC_CHUNK_BYTES, size - off);
|
|
1992
|
+
const b = base64ToBytes(await this.transferExec(pullChunkCmd(tmp, off, want), envs, PULL_MARK, signal));
|
|
1993
|
+
if (b.length !== want) throw new InstaboxError("the archive changed while reading it", { code: "file_changed" });
|
|
1994
|
+
yield b;
|
|
1995
|
+
}
|
|
1996
|
+
}
|
|
1997
|
+
/**
|
|
1998
|
+
* @internal Stages bytes as a temporary file for a command's stdin (`instabox exec --stdin`'s way) and
|
|
1999
|
+
* returns its path. The command removes it as it starts.
|
|
2000
|
+
*/
|
|
2001
|
+
async stageStdin(bytes, signal) {
|
|
2002
|
+
const p = STDIN_TMP_PREFIX + randomHex();
|
|
2003
|
+
await this.putTemp(p, bytes, signal);
|
|
2004
|
+
return p;
|
|
2005
|
+
}
|
|
1045
2006
|
/** The file routes take absolute paths; a relative one is relative to exec's working directory (HOME). */
|
|
1046
2007
|
async absolute(path) {
|
|
1047
2008
|
if (path.startsWith("/")) return path;
|
|
@@ -1087,6 +2048,121 @@ var Files = class {
|
|
|
1087
2048
|
function arg(path) {
|
|
1088
2049
|
return shellQuote(path.startsWith("-") ? `./${path}` : path);
|
|
1089
2050
|
}
|
|
2051
|
+
function tooLargeForExec() {
|
|
2052
|
+
return new InstaboxError(
|
|
2053
|
+
`data is larger than the ${MAX_FILE_BYTES}-byte limit of files.write on a server without the file routes`,
|
|
2054
|
+
{ code: "file_too_large" }
|
|
2055
|
+
);
|
|
2056
|
+
}
|
|
2057
|
+
function noRoutes() {
|
|
2058
|
+
return new InstaboxError("this server has no file routes (PUT /v1/machines/{id}/files) to stream to", {
|
|
2059
|
+
status: 404,
|
|
2060
|
+
code: "unsupported"
|
|
2061
|
+
});
|
|
2062
|
+
}
|
|
2063
|
+
function bufferedTimeout(size) {
|
|
2064
|
+
return Math.min(TRANSFER_MAX_MS, Math.max(TRANSFER_TIMEOUT_MS, Math.ceil(size / 65536) * 1e3));
|
|
2065
|
+
}
|
|
2066
|
+
function asBytes(data) {
|
|
2067
|
+
if (typeof data === "string") return new TextEncoder().encode(data);
|
|
2068
|
+
if (data instanceof Uint8Array) return data;
|
|
2069
|
+
if (data instanceof ArrayBuffer) return new Uint8Array(data);
|
|
2070
|
+
return void 0;
|
|
2071
|
+
}
|
|
2072
|
+
function asIterable(data) {
|
|
2073
|
+
const d = data;
|
|
2074
|
+
if (d && typeof d[Symbol.asyncIterator] === "function") return data;
|
|
2075
|
+
if (d && typeof d.getReader === "function") return iterable(data);
|
|
2076
|
+
throw new InstaboxError(
|
|
2077
|
+
"files.write takes a string, a Uint8Array, an ArrayBuffer, a ReadableStream or an AsyncIterable of chunks",
|
|
2078
|
+
{ code: "bad_request" }
|
|
2079
|
+
);
|
|
2080
|
+
}
|
|
2081
|
+
function chunkBytes(chunk) {
|
|
2082
|
+
if (chunk instanceof Uint8Array) return chunk;
|
|
2083
|
+
if (typeof chunk === "string") return new TextEncoder().encode(chunk);
|
|
2084
|
+
if (chunk instanceof ArrayBuffer) return new Uint8Array(chunk);
|
|
2085
|
+
throw new InstaboxError("a stream given to files.write yielded something other than bytes or a string", {
|
|
2086
|
+
code: "bad_request"
|
|
2087
|
+
});
|
|
2088
|
+
}
|
|
2089
|
+
function sourceError(err) {
|
|
2090
|
+
if (err instanceof InstaboxError) return err;
|
|
2091
|
+
const msg = err?.message ?? String(err);
|
|
2092
|
+
return new InstaboxError(`reading the data to write failed: ${msg}`, { code: "source_error", cause: err });
|
|
2093
|
+
}
|
|
2094
|
+
async function collect(src, limit) {
|
|
2095
|
+
const parts = [];
|
|
2096
|
+
let n = 0;
|
|
2097
|
+
try {
|
|
2098
|
+
for await (const c of src) {
|
|
2099
|
+
const b = chunkBytes(c);
|
|
2100
|
+
n += b.length;
|
|
2101
|
+
if (n > limit) throw tooLargeForExec();
|
|
2102
|
+
parts.push(b);
|
|
2103
|
+
}
|
|
2104
|
+
} catch (err) {
|
|
2105
|
+
throw sourceError(err);
|
|
2106
|
+
}
|
|
2107
|
+
return concat(parts, n);
|
|
2108
|
+
}
|
|
2109
|
+
function concat(parts, n) {
|
|
2110
|
+
const out = new Uint8Array(n);
|
|
2111
|
+
let off = 0;
|
|
2112
|
+
for (const p of parts) {
|
|
2113
|
+
out.set(p, off);
|
|
2114
|
+
off += p.length;
|
|
2115
|
+
}
|
|
2116
|
+
return out;
|
|
2117
|
+
}
|
|
2118
|
+
async function* rechunk(src, size) {
|
|
2119
|
+
let buf = new Uint8Array(size);
|
|
2120
|
+
let n = 0;
|
|
2121
|
+
for await (const c of src) {
|
|
2122
|
+
let b = chunkBytes(c);
|
|
2123
|
+
while (b.length) {
|
|
2124
|
+
const take = Math.min(size - n, b.length);
|
|
2125
|
+
buf.set(b.subarray(0, take), n);
|
|
2126
|
+
n += take;
|
|
2127
|
+
b = b.subarray(take);
|
|
2128
|
+
if (n === size) {
|
|
2129
|
+
yield buf;
|
|
2130
|
+
buf = new Uint8Array(size);
|
|
2131
|
+
n = 0;
|
|
2132
|
+
}
|
|
2133
|
+
}
|
|
2134
|
+
}
|
|
2135
|
+
if (n) yield buf.subarray(0, n);
|
|
2136
|
+
}
|
|
2137
|
+
function oneChunk(bytes) {
|
|
2138
|
+
return new ReadableStream({
|
|
2139
|
+
start(c) {
|
|
2140
|
+
if (bytes.length) c.enqueue(bytes);
|
|
2141
|
+
c.close();
|
|
2142
|
+
}
|
|
2143
|
+
});
|
|
2144
|
+
}
|
|
2145
|
+
function iterable(stream) {
|
|
2146
|
+
const s = stream;
|
|
2147
|
+
if (typeof s[Symbol.asyncIterator] !== "function") {
|
|
2148
|
+
Object.defineProperty(s, Symbol.asyncIterator, {
|
|
2149
|
+
configurable: true,
|
|
2150
|
+
value: async function* () {
|
|
2151
|
+
const reader = stream.getReader();
|
|
2152
|
+
try {
|
|
2153
|
+
for (; ; ) {
|
|
2154
|
+
const { done, value } = await reader.read();
|
|
2155
|
+
if (done) return;
|
|
2156
|
+
yield value;
|
|
2157
|
+
}
|
|
2158
|
+
} finally {
|
|
2159
|
+
reader.releaseLock();
|
|
2160
|
+
}
|
|
2161
|
+
}
|
|
2162
|
+
});
|
|
2163
|
+
}
|
|
2164
|
+
return s;
|
|
2165
|
+
}
|
|
1090
2166
|
async function readBody(res, limit, path) {
|
|
1091
2167
|
const tooLarge = () => new InstaboxError(`${path} is larger than the ${limit}-byte limit of files.read`, { code: "file_too_large" });
|
|
1092
2168
|
const reader = res.body?.getReader();
|
|
@@ -1113,13 +2189,7 @@ async function readBody(res, limit, path) {
|
|
|
1113
2189
|
cause: err
|
|
1114
2190
|
});
|
|
1115
2191
|
}
|
|
1116
|
-
|
|
1117
|
-
let off = 0;
|
|
1118
|
-
for (const c of chunks) {
|
|
1119
|
-
out.set(c, off);
|
|
1120
|
-
off += c.length;
|
|
1121
|
-
}
|
|
1122
|
-
return out;
|
|
2192
|
+
return concat(chunks, n);
|
|
1123
2193
|
}
|
|
1124
2194
|
function routeMissing(err) {
|
|
1125
2195
|
if (!(err instanceof InstaboxError)) return false;
|
|
@@ -1132,6 +2202,14 @@ async function sha256Hex(bytes) {
|
|
|
1132
2202
|
const d = new Uint8Array(await subtle.digest("SHA-256", bytes));
|
|
1133
2203
|
return Array.from(d, (x) => x.toString(16).padStart(2, "0")).join("");
|
|
1134
2204
|
}
|
|
2205
|
+
async function sha256Stream() {
|
|
2206
|
+
try {
|
|
2207
|
+
const c = await import("node:crypto");
|
|
2208
|
+
return c.createHash("sha256");
|
|
2209
|
+
} catch {
|
|
2210
|
+
return void 0;
|
|
2211
|
+
}
|
|
2212
|
+
}
|
|
1135
2213
|
function writeError(result, path) {
|
|
1136
2214
|
if (result.exitCode === 21) return new InstaboxError(`is a directory: ${path}`, { code: "is_a_directory" });
|
|
1137
2215
|
return new CommandExitError(result);
|
|
@@ -1218,30 +2296,33 @@ var HttpClient = class {
|
|
|
1218
2296
|
async send(method, path, opts = {}) {
|
|
1219
2297
|
const isRead = method === "GET" || method === "HEAD";
|
|
1220
2298
|
const idempotent = opts.idempotent ?? !isRead;
|
|
1221
|
-
const retry = opts.retry ?? (isRead || idempotent);
|
|
1222
|
-
const
|
|
2299
|
+
const retry = opts.streamBody ? false : opts.retry ?? (isRead || idempotent);
|
|
2300
|
+
const headers2 = {
|
|
1223
2301
|
"X-API-Key": this.#apiKey,
|
|
1224
2302
|
Accept: opts.accept ?? "application/json",
|
|
1225
2303
|
...opts.headers
|
|
1226
2304
|
};
|
|
1227
|
-
if (idempotent)
|
|
2305
|
+
if (idempotent) headers2["Idempotency-Key"] = uuid();
|
|
1228
2306
|
let body;
|
|
1229
|
-
if (opts.
|
|
1230
|
-
|
|
2307
|
+
if (opts.streamBody !== void 0) {
|
|
2308
|
+
headers2["Content-Type"] = "application/octet-stream";
|
|
2309
|
+
body = opts.streamBody;
|
|
2310
|
+
} else if (opts.rawBody !== void 0) {
|
|
2311
|
+
headers2["Content-Type"] = "application/octet-stream";
|
|
1231
2312
|
body = opts.rawBody;
|
|
1232
2313
|
} else if (opts.body !== void 0) {
|
|
1233
|
-
|
|
2314
|
+
headers2["Content-Type"] = "application/json";
|
|
1234
2315
|
body = JSON.stringify(opts.body);
|
|
1235
2316
|
}
|
|
1236
2317
|
const where = this.#redact(`${method} ${path}`);
|
|
1237
2318
|
let url = this.apiUrl + path;
|
|
1238
2319
|
if (opts.query) {
|
|
1239
|
-
const
|
|
2320
|
+
const q2 = new URLSearchParams();
|
|
1240
2321
|
for (const [k, v] of Object.entries(opts.query)) {
|
|
1241
|
-
if (Array.isArray(v)) for (const item of v)
|
|
1242
|
-
else if (v !== void 0)
|
|
2322
|
+
if (Array.isArray(v)) for (const item of v) q2.append(k, item);
|
|
2323
|
+
else if (v !== void 0) q2.set(k, String(v));
|
|
1243
2324
|
}
|
|
1244
|
-
const s =
|
|
2325
|
+
const s = q2.toString();
|
|
1245
2326
|
if (s) url += `?${s}`;
|
|
1246
2327
|
}
|
|
1247
2328
|
for (let attempt = 0; ; attempt++) {
|
|
@@ -1258,7 +2339,12 @@ var HttpClient = class {
|
|
|
1258
2339
|
else opts.signal?.addEventListener("abort", onAbort, { once: true });
|
|
1259
2340
|
let res;
|
|
1260
2341
|
try {
|
|
1261
|
-
|
|
2342
|
+
const init = { method, headers: headers2, body, signal: ctrl.signal };
|
|
2343
|
+
if (opts.streamBody !== void 0) {
|
|
2344
|
+
init.duplex = "half";
|
|
2345
|
+
init.redirect = "error";
|
|
2346
|
+
}
|
|
2347
|
+
res = await this.fetchImpl(url, init);
|
|
1262
2348
|
} catch (err) {
|
|
1263
2349
|
clearTimeout(timer);
|
|
1264
2350
|
opts.signal?.removeEventListener("abort", onAbort);
|
|
@@ -1454,7 +2540,7 @@ function toSeconds(ms, field) {
|
|
|
1454
2540
|
return s;
|
|
1455
2541
|
}
|
|
1456
2542
|
var METADATA_KEY = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
1457
|
-
var
|
|
2543
|
+
var enc3 = encodeURIComponent;
|
|
1458
2544
|
var Sandbox = class _Sandbox {
|
|
1459
2545
|
constructor(http, machine, opts = {}) {
|
|
1460
2546
|
this.http = http;
|
|
@@ -1462,6 +2548,7 @@ var Sandbox = class _Sandbox {
|
|
|
1462
2548
|
this.machine = machine;
|
|
1463
2549
|
this.commands = new Commands(http, machine.id, { ...opts.envs });
|
|
1464
2550
|
this.files = new Files(this.commands, http, machine.id);
|
|
2551
|
+
this.commands.stageStdin = (bytes, signal) => this.files.stageStdin(bytes, signal);
|
|
1465
2552
|
this.desktop = new Desktop(http, machine.id, this.commands, this.files);
|
|
1466
2553
|
}
|
|
1467
2554
|
http;
|
|
@@ -1552,12 +2639,12 @@ var Sandbox = class _Sandbox {
|
|
|
1552
2639
|
}
|
|
1553
2640
|
/** Fetches a snapshot by ID. Requires images:read. */
|
|
1554
2641
|
static async getSnapshot(snapshotId, opts = {}) {
|
|
1555
|
-
return new HttpClient(opts).request("GET", `/v1/snapshots/${
|
|
2642
|
+
return new HttpClient(opts).request("GET", `/v1/snapshots/${enc3(snapshotId)}`);
|
|
1556
2643
|
}
|
|
1557
2644
|
/** Deletes a snapshot. Returns false if absent. Requires images:delete. */
|
|
1558
2645
|
static async deleteSnapshot(snapshotId, opts = {}) {
|
|
1559
2646
|
try {
|
|
1560
|
-
await new HttpClient(opts).request("DELETE", `/v1/snapshots/${
|
|
2647
|
+
await new HttpClient(opts).request("DELETE", `/v1/snapshots/${enc3(snapshotId)}`);
|
|
1561
2648
|
return true;
|
|
1562
2649
|
} catch (err) {
|
|
1563
2650
|
if (err instanceof InstaboxError && err.status === 404 && err.code === "not_found") return false;
|
|
@@ -1572,7 +2659,7 @@ var Sandbox = class _Sandbox {
|
|
|
1572
2659
|
async createSnapshot(opts) {
|
|
1573
2660
|
await this.settle();
|
|
1574
2661
|
await this.untilSynced();
|
|
1575
|
-
return this.http.request("POST", `/v1/machines/${
|
|
2662
|
+
return this.http.request("POST", `/v1/machines/${enc3(this.sandboxId)}/snapshots`, { body: opts });
|
|
1576
2663
|
}
|
|
1577
2664
|
/** This sandbox's recent CPU and memory samples; see `Sandbox.getMetrics`. */
|
|
1578
2665
|
async getMetrics(opts = {}) {
|
|
@@ -1592,7 +2679,7 @@ var Sandbox = class _Sandbox {
|
|
|
1592
2679
|
* pause off. The setting stays across pause and resume.
|
|
1593
2680
|
*/
|
|
1594
2681
|
async setAutoSuspend(idleMs) {
|
|
1595
|
-
this.machine = await this.http.request("PATCH", `/v1/machines/${
|
|
2682
|
+
this.machine = await this.http.request("PATCH", `/v1/machines/${enc3(this.sandboxId)}`, {
|
|
1596
2683
|
body: { autoSuspendAfterSeconds: toIdleSeconds(idleMs) }
|
|
1597
2684
|
});
|
|
1598
2685
|
}
|
|
@@ -1606,7 +2693,7 @@ var Sandbox = class _Sandbox {
|
|
|
1606
2693
|
}
|
|
1607
2694
|
/** Replaces the sandbox's metadata (`{}` clears it). */
|
|
1608
2695
|
async setMetadata(metadata) {
|
|
1609
|
-
this.machine = await this.http.request("PATCH", `/v1/machines/${
|
|
2696
|
+
this.machine = await this.http.request("PATCH", `/v1/machines/${enc3(this.sandboxId)}`, {
|
|
1610
2697
|
body: { metadata }
|
|
1611
2698
|
});
|
|
1612
2699
|
}
|
|
@@ -1616,21 +2703,21 @@ var Sandbox = class _Sandbox {
|
|
|
1616
2703
|
* Throws `not_found` on a server without the Vault.
|
|
1617
2704
|
*/
|
|
1618
2705
|
async vault() {
|
|
1619
|
-
return this.http.request("GET", `/v1/machines/${
|
|
2706
|
+
return this.http.request("GET", `/v1/machines/${enc3(this.sandboxId)}/vault`);
|
|
1620
2707
|
}
|
|
1621
2708
|
/**
|
|
1622
2709
|
* Writes the account's current Vault items into the running sandbox now, the same write as after a boot,
|
|
1623
2710
|
* and returns its record (`error` set when the guest refused it). Requires machines:write.
|
|
1624
2711
|
*/
|
|
1625
2712
|
async pushVault() {
|
|
1626
|
-
return this.http.request("POST", `/v1/machines/${
|
|
2713
|
+
return this.http.request("POST", `/v1/machines/${enc3(this.sandboxId)}/vault`);
|
|
1627
2714
|
}
|
|
1628
2715
|
/**
|
|
1629
2716
|
* Turns the Vault off for this sandbox, for good, in any state: its next boot, resume or push removes
|
|
1630
2717
|
* what the Vault wrote and nothing is written again. Requires machines:write.
|
|
1631
2718
|
*/
|
|
1632
2719
|
async disableVault() {
|
|
1633
|
-
this.machine = await this.http.request("PATCH", `/v1/machines/${
|
|
2720
|
+
this.machine = await this.http.request("PATCH", `/v1/machines/${enc3(this.sandboxId)}`, {
|
|
1634
2721
|
body: { vault: false }
|
|
1635
2722
|
});
|
|
1636
2723
|
}
|
|
@@ -1677,7 +2764,7 @@ var Sandbox = class _Sandbox {
|
|
|
1677
2764
|
}
|
|
1678
2765
|
body.ttlSeconds = opts.ttlSeconds;
|
|
1679
2766
|
}
|
|
1680
|
-
const c = await this.http.request("POST", `/v1/machines/${
|
|
2767
|
+
const c = await this.http.request("POST", `/v1/machines/${enc3(this.sandboxId)}/connections`, { body });
|
|
1681
2768
|
return {
|
|
1682
2769
|
host: c.host,
|
|
1683
2770
|
port: c.port,
|
|
@@ -1696,7 +2783,7 @@ var Sandbox = class _Sandbox {
|
|
|
1696
2783
|
async settle(refresh = true) {
|
|
1697
2784
|
if (refresh) this.machine = await getMachine(this.http, this.sandboxId);
|
|
1698
2785
|
if (this.machine.operationId) {
|
|
1699
|
-
const op = await this.http.request("GET", `/v1/operations/${
|
|
2786
|
+
const op = await this.http.request("GET", `/v1/operations/${enc3(this.machine.operationId)}`);
|
|
1700
2787
|
await this.http.waitForOperation(op).catch(() => {
|
|
1701
2788
|
});
|
|
1702
2789
|
this.machine = await getMachine(this.http, this.sandboxId);
|
|
@@ -1724,29 +2811,29 @@ var Sandbox = class _Sandbox {
|
|
|
1724
2811
|
}
|
|
1725
2812
|
}
|
|
1726
2813
|
async mutate(method, action) {
|
|
1727
|
-
const op = await this.http.request(method, `/v1/machines/${
|
|
2814
|
+
const op = await this.http.request(method, `/v1/machines/${enc3(this.sandboxId)}/${action}`);
|
|
1728
2815
|
await this.http.waitForOperation(op);
|
|
1729
2816
|
this.machine = await getMachine(this.http, this.sandboxId);
|
|
1730
2817
|
}
|
|
1731
2818
|
};
|
|
1732
2819
|
async function getMachine(http, id) {
|
|
1733
|
-
return http.request("GET", `/v1/machines/${
|
|
2820
|
+
return http.request("GET", `/v1/machines/${enc3(id)}`);
|
|
1734
2821
|
}
|
|
1735
2822
|
async function getMetrics(http, id, opts) {
|
|
1736
|
-
const out = await http.request("GET", `/v1/machines/${
|
|
2823
|
+
const out = await http.request("GET", `/v1/machines/${enc3(id)}/metrics`, {
|
|
1737
2824
|
query: { since: opts.since?.toISOString() }
|
|
1738
2825
|
});
|
|
1739
2826
|
return out.metrics.map((s) => ({ ...s, timestamp: new Date(s.timestamp) }));
|
|
1740
2827
|
}
|
|
1741
2828
|
async function getUsage(http, id, opts) {
|
|
1742
|
-
const u = await http.request("GET", `/v1/machines/${
|
|
2829
|
+
const u = await http.request("GET", `/v1/machines/${enc3(id)}/usage`, {
|
|
1743
2830
|
query: { from: opts.from?.toISOString(), to: opts.to?.toISOString() }
|
|
1744
2831
|
});
|
|
1745
2832
|
return { ...u, from: new Date(u.from), to: new Date(u.to) };
|
|
1746
2833
|
}
|
|
1747
2834
|
async function killMachine(http, id) {
|
|
1748
2835
|
try {
|
|
1749
|
-
const op = await http.request("DELETE", `/v1/machines/${
|
|
2836
|
+
const op = await http.request("DELETE", `/v1/machines/${enc3(id)}`, {
|
|
1750
2837
|
headers: { "X-Confirm-Delete": id }
|
|
1751
2838
|
});
|
|
1752
2839
|
await http.waitForOperation(op);
|