@insforge/instabox-sdk 0.6.0 → 0.7.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/README.md +63 -19
- package/dist/index.cjs +1141 -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 +1131 -85
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/skills/instabox/SKILL.md +5 -4
package/dist/index.js
CHANGED
|
@@ -250,6 +250,13 @@ function toResult(res, stdout = res.stdout, stderr = res.stderr) {
|
|
|
250
250
|
if (typeof res.error === "string" && res.error) out.error = res.error;
|
|
251
251
|
return out;
|
|
252
252
|
}
|
|
253
|
+
function utf8Text(bytes) {
|
|
254
|
+
try {
|
|
255
|
+
return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
|
|
256
|
+
} catch {
|
|
257
|
+
return void 0;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
253
260
|
var Commands = class {
|
|
254
261
|
/** @internal */
|
|
255
262
|
constructor(http, sandboxId, defaultEnvs) {
|
|
@@ -260,9 +267,43 @@ var Commands = class {
|
|
|
260
267
|
http;
|
|
261
268
|
sandboxId;
|
|
262
269
|
defaultEnvs;
|
|
270
|
+
/**
|
|
271
|
+
* @internal Uploads stdin the exec request cannot carry to a temporary file and returns its path
|
|
272
|
+
* (set by `Sandbox`, which owns the file routes).
|
|
273
|
+
*/
|
|
274
|
+
stageStdin;
|
|
263
275
|
async run(cmd, opts = {}) {
|
|
264
276
|
if (opts.background) return this.startJob(cmd, opts);
|
|
265
|
-
|
|
277
|
+
let o = opts;
|
|
278
|
+
let staged;
|
|
279
|
+
if (opts.stdin !== void 0) {
|
|
280
|
+
const bytes = typeof opts.stdin === "string" ? new TextEncoder().encode(opts.stdin) : opts.stdin;
|
|
281
|
+
if (!(bytes instanceof Uint8Array)) {
|
|
282
|
+
throw new InstaboxError("stdin must be a string or a Uint8Array", { code: "bad_request" });
|
|
283
|
+
}
|
|
284
|
+
const text = bytes.length <= MAX_STDIN_BYTES ? utf8Text(bytes) : void 0;
|
|
285
|
+
if (text !== void 0) o = { ...opts, stdin: text };
|
|
286
|
+
else {
|
|
287
|
+
if (!this.stageStdin) {
|
|
288
|
+
throw new InstaboxError(`stdin is longer than ${MAX_STDIN_BYTES} bytes or not UTF-8 text`, {
|
|
289
|
+
code: "bad_request"
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
staged = await this.stageStdin(bytes, opts.signal);
|
|
293
|
+
const q2 = shellQuote(staged);
|
|
294
|
+
cmd = `exec <${q2} || exit 1
|
|
295
|
+
rm -f -- ${q2}
|
|
296
|
+
${cmd}`;
|
|
297
|
+
o = { ...opts, stdin: void 0 };
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
let r;
|
|
301
|
+
try {
|
|
302
|
+
r = o.onStdout || o.onStderr ? await this.execStream(cmd, o) : await this.exec(cmd, o);
|
|
303
|
+
} finally {
|
|
304
|
+
if (staged && !r) await this.exec(`rm -f -- ${shellQuote(staged)}`, { noHistory: true }).catch(() => {
|
|
305
|
+
});
|
|
306
|
+
}
|
|
266
307
|
if (r.exitCode !== 0) throw new CommandExitError(r);
|
|
267
308
|
return r;
|
|
268
309
|
}
|
|
@@ -376,7 +417,7 @@ var Commands = class {
|
|
|
376
417
|
}
|
|
377
418
|
/** Reads a streamed exec's server-sent events until its `exit` or `error` event. */
|
|
378
419
|
async readEvents(reader, opts, fail) {
|
|
379
|
-
const
|
|
420
|
+
const dec2 = new TextDecoder();
|
|
380
421
|
const out = { stdout: "", stderr: "" };
|
|
381
422
|
let buf = "";
|
|
382
423
|
let event = "";
|
|
@@ -389,7 +430,7 @@ var Commands = class {
|
|
|
389
430
|
throw fail(streamEnded());
|
|
390
431
|
}
|
|
391
432
|
if (chunk.done) throw fail(streamEnded());
|
|
392
|
-
buf +=
|
|
433
|
+
buf += dec2.decode(chunk.value, { stream: true });
|
|
393
434
|
let start = 0;
|
|
394
435
|
for (let nl = buf.indexOf("\n", start); nl >= 0; nl = buf.indexOf("\n", start)) {
|
|
395
436
|
let line = buf.slice(start, nl);
|
|
@@ -533,7 +574,7 @@ ${value}`;
|
|
|
533
574
|
throw new InstaboxError("wait timeoutMs must be greater than 0", { code: "bad_request" });
|
|
534
575
|
const until = opts.timeoutMs === void 0 ? Infinity : Date.now() + opts.timeoutMs;
|
|
535
576
|
const maxWait = Math.max(0, Math.min(JOB_POLL_SEC, Math.floor((this.http.requestTimeout(Infinity) - 5e3) / 1e3)));
|
|
536
|
-
const
|
|
577
|
+
const dec2 = new TextDecoder();
|
|
537
578
|
let stdout = "";
|
|
538
579
|
let off = 0;
|
|
539
580
|
let idle = JOB_IDLE_MIN_MS;
|
|
@@ -552,10 +593,10 @@ ${value}`;
|
|
|
552
593
|
idle = Math.min(idle * 2, JOB_IDLE_MAX_MS);
|
|
553
594
|
} else if (read.bytes.length > 0) idle = JOB_IDLE_MIN_MS;
|
|
554
595
|
off += read.bytes.length;
|
|
555
|
-
await emit(
|
|
596
|
+
await emit(dec2.decode(read.bytes, { stream: true }));
|
|
556
597
|
if (read.bytes.length === JOB_CHUNK) continue;
|
|
557
598
|
if (read.status !== "running") {
|
|
558
|
-
await emit(
|
|
599
|
+
await emit(dec2.decode());
|
|
559
600
|
if (read.exitCode === void 0) {
|
|
560
601
|
throw new InstaboxError(
|
|
561
602
|
`job ${jobId} ended without an exit code (the sandbox restarted or the job was killed)`,
|
|
@@ -830,11 +871,503 @@ var Desktop = class {
|
|
|
830
871
|
}
|
|
831
872
|
};
|
|
832
873
|
|
|
874
|
+
// src/guest.ts
|
|
875
|
+
var TRANSFER_TMP_PREFIX = "/tmp/.instabox-transfer-";
|
|
876
|
+
var STDIN_TMP_PREFIX = "/tmp/.instabox-stdin-";
|
|
877
|
+
var PUSH_MARK = "INSTABOX-PUSH\0";
|
|
878
|
+
var PULL_MARK = "INSTABOX-PULL\0";
|
|
879
|
+
var EXEC_CHUNK_BYTES = 768e3;
|
|
880
|
+
var GUEST_FNS = `fsize() { local n; n=$(wc -c < "$1") && echo $((n)); }
|
|
881
|
+
fmode() { stat -c %a -- "$1" 2>/dev/null || stat -f %Lp -- "$1"; }
|
|
882
|
+
b64() { base64 | tr -d '\\n'; }
|
|
883
|
+
rng() { { dd bs=1 skip="$2" count=0 2>/dev/null; head -c "$3"; } < "$1"; }
|
|
884
|
+
rpe() { readlink -e -- "$1" 2>/dev/null || { [ -e "$1" ] && rpm "$1"; }; }
|
|
885
|
+
rpm() {
|
|
886
|
+
realpath -m -- "$1" 2>/dev/null && return
|
|
887
|
+
local r; r=$(readlink -f -- "$1" 2>/dev/null) && [ -n "$r" ] && { printf '%s\\n' "$r"; return; }
|
|
888
|
+
r=$(CDPATH= cd -P -- "$(dirname -- "$1")" 2>/dev/null && pwd -P) && { printf '%s/%s\\n' "\${r%/}" "$(basename -- "$1")"; return; }
|
|
889
|
+
case $1 in /*) printf '%s\\n' "$1" ;; *) printf '%s\\n' "$PWD/$1" ;; esac
|
|
890
|
+
}
|
|
891
|
+
`;
|
|
892
|
+
var PUSH_CHUNK_SCRIPT = `if [ "$IB_FIRST" = 1 ]; then (umask 077; set -C; base64 -d > "$IB_TMP"); else base64 -d >> "$IB_TMP"; fi
|
|
893
|
+
`;
|
|
894
|
+
var PUSH_FINISH_SCRIPT = `set -eo pipefail
|
|
895
|
+
trap 'rm -f -- "$IB_TMP"' EXIT
|
|
896
|
+
${GUEST_FNS}d=$IB_DEST
|
|
897
|
+
case $d in "~") d=$HOME ;; "~/"*) d=$HOME/\${d#"~/"} ;; esac
|
|
898
|
+
mkdir -p -- "$d"
|
|
899
|
+
tar -xzf "$IB_TMP" -C "$d" --no-same-owner
|
|
900
|
+
printf 'INSTABOX-PUSH\\0ok\\0%s\\0' "$(rpm "$d")"
|
|
901
|
+
`;
|
|
902
|
+
var PULL_START = `${GUEST_FNS}set -eo pipefail
|
|
903
|
+
printf 'INSTABOX-PULL\\0'
|
|
904
|
+
r=$(rpe "$1") || { printf 'missing\\0'; exit 0; }
|
|
905
|
+
[ -d "$r" ] || { printf 'not_a_dir\\0%s\\0' "$r"; exit 0; }
|
|
906
|
+
umask 077
|
|
907
|
+
trap '[ "$ok" = 1 ] || rm -f -- "$2"' EXIT
|
|
908
|
+
COPYFILE_DISABLE=1 tar -czf "$2" -C "$r" .
|
|
909
|
+
printf 'dir\\0%s\\0%s\\0' "$r" "$(fsize "$2")"
|
|
910
|
+
ok=1
|
|
911
|
+
`;
|
|
912
|
+
var PULL_CHUNK = `${GUEST_FNS}set -eo pipefail
|
|
913
|
+
printf 'INSTABOX-PULL\\0'
|
|
914
|
+
rng "$3" "$2" "$4" | b64
|
|
915
|
+
`;
|
|
916
|
+
var PULL_REMOVE = `rm -f -- "$2"`;
|
|
917
|
+
function q(s) {
|
|
918
|
+
return `'${s.replace(/'/g, `'\\''`)}'`;
|
|
919
|
+
}
|
|
920
|
+
function pullCmd(script, ...args) {
|
|
921
|
+
const run2 = `bash -c "$S" _ "$p" ${args.map(q).join(" ")}`;
|
|
922
|
+
return `S=${q(script)}
|
|
923
|
+
p=$IB_PATH; case $p in "~") p=$HOME ;; "~/"*) p=$HOME/\${p#"~/"} ;; esac; case $p in /*) ;; *) p=$PWD/$p ;; esac
|
|
924
|
+
if sudo -n true 2>/dev/null; then exec sudo -n ${run2}; else exec ${run2}; fi`;
|
|
925
|
+
}
|
|
926
|
+
var pullStartCmd = (tmp) => pullCmd(PULL_START, tmp);
|
|
927
|
+
var pullChunkCmd = (tmp, off, n) => pullCmd(PULL_CHUNK, String(off), tmp, String(n));
|
|
928
|
+
var pullRemoveCmd = (tmp) => pullCmd(PULL_REMOVE, tmp);
|
|
929
|
+
function randomHex(bytes = 8) {
|
|
930
|
+
const b = new Uint8Array(bytes);
|
|
931
|
+
const c = globalThis.crypto;
|
|
932
|
+
if (c?.getRandomValues) c.getRandomValues(b);
|
|
933
|
+
else for (let i = 0; i < bytes; i++) b[i] = Math.floor(Math.random() * 256);
|
|
934
|
+
return Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
// src/tar.ts
|
|
938
|
+
var BLOCK = 512;
|
|
939
|
+
var enc2 = new TextEncoder();
|
|
940
|
+
var dec = new TextDecoder();
|
|
941
|
+
function octal(buf, off, width, value) {
|
|
942
|
+
const s = Math.floor(value).toString(8).padStart(width - 1, "0");
|
|
943
|
+
buf.set(enc2.encode(s.slice(-(width - 1))), off);
|
|
944
|
+
buf[off + width - 1] = 0;
|
|
945
|
+
}
|
|
946
|
+
function putString(buf, off, width, s) {
|
|
947
|
+
buf.set(enc2.encode(s).subarray(0, width), off);
|
|
948
|
+
}
|
|
949
|
+
function isAscii(s) {
|
|
950
|
+
return /^[\x20-\x7e]*$/.test(s);
|
|
951
|
+
}
|
|
952
|
+
function paxRecord(key, value) {
|
|
953
|
+
const body = ` ${key}=${value}
|
|
954
|
+
`;
|
|
955
|
+
const n = enc2.encode(body).length;
|
|
956
|
+
let len = n + String(n).length;
|
|
957
|
+
if (String(len).length !== String(n).length) len = n + String(len).length;
|
|
958
|
+
return `${len}${body}`;
|
|
959
|
+
}
|
|
960
|
+
function header(name, type, mode, mtime, size, linkname) {
|
|
961
|
+
const h = new Uint8Array(BLOCK);
|
|
962
|
+
putString(h, 0, 100, name);
|
|
963
|
+
octal(h, 100, 8, mode & 4095);
|
|
964
|
+
octal(h, 108, 8, 0);
|
|
965
|
+
octal(h, 116, 8, 0);
|
|
966
|
+
octal(h, 124, 12, size);
|
|
967
|
+
octal(h, 136, 12, Math.max(0, mtime));
|
|
968
|
+
h.fill(32, 148, 156);
|
|
969
|
+
h[156] = type.charCodeAt(0);
|
|
970
|
+
putString(h, 157, 100, linkname);
|
|
971
|
+
putString(h, 257, 6, "ustar\0");
|
|
972
|
+
putString(h, 263, 2, "00");
|
|
973
|
+
let sum = 0;
|
|
974
|
+
for (const b of h) sum += b;
|
|
975
|
+
const s = sum.toString(8).padStart(6, "0");
|
|
976
|
+
putString(h, 148, 6, s);
|
|
977
|
+
h[154] = 0;
|
|
978
|
+
h[155] = 32;
|
|
979
|
+
return h;
|
|
980
|
+
}
|
|
981
|
+
var USTAR_MAX_SIZE = 8589934591;
|
|
982
|
+
function headers(e) {
|
|
983
|
+
const name = e.type === "dir" ? `${e.name}/` : e.name;
|
|
984
|
+
const link = e.linkname ?? "";
|
|
985
|
+
const size = e.type === "file" ? e.size ?? 0 : 0;
|
|
986
|
+
const pax = [];
|
|
987
|
+
if (enc2.encode(name).length > 100 || !isAscii(name)) pax.push(paxRecord("path", name));
|
|
988
|
+
if (enc2.encode(link).length > 100 || !isAscii(link)) pax.push(paxRecord("linkpath", link));
|
|
989
|
+
if (size > USTAR_MAX_SIZE) pax.push(paxRecord("size", String(size)));
|
|
990
|
+
const type = e.type === "dir" ? "5" : e.type === "symlink" ? "2" : "0";
|
|
991
|
+
const out = [];
|
|
992
|
+
if (pax.length) {
|
|
993
|
+
const data = enc2.encode(pax.join(""));
|
|
994
|
+
out.push(header("PaxHeader", "x", 420, e.mtime, data.length, ""));
|
|
995
|
+
out.push(padded(data));
|
|
996
|
+
}
|
|
997
|
+
out.push(
|
|
998
|
+
header(asciiPrefix(name, 100), type, e.mode, e.mtime, size > USTAR_MAX_SIZE ? 0 : size, asciiPrefix(link, 100))
|
|
999
|
+
);
|
|
1000
|
+
return out;
|
|
1001
|
+
}
|
|
1002
|
+
function asciiPrefix(s, max) {
|
|
1003
|
+
return s.replace(/[^\x20-\x7e]/g, "_").slice(0, max);
|
|
1004
|
+
}
|
|
1005
|
+
function padded(data) {
|
|
1006
|
+
const n = Math.ceil(data.length / BLOCK) * BLOCK;
|
|
1007
|
+
if (n === data.length) return data;
|
|
1008
|
+
const out = new Uint8Array(n);
|
|
1009
|
+
out.set(data);
|
|
1010
|
+
return out;
|
|
1011
|
+
}
|
|
1012
|
+
async function* tarStream(entries) {
|
|
1013
|
+
for await (const e of entries) {
|
|
1014
|
+
for (const h of headers(e)) yield h;
|
|
1015
|
+
if (e.type !== "file") continue;
|
|
1016
|
+
const size = e.size ?? 0;
|
|
1017
|
+
let n = 0;
|
|
1018
|
+
if (e.data) {
|
|
1019
|
+
for await (const chunk of e.data()) {
|
|
1020
|
+
if (n + chunk.length > size) {
|
|
1021
|
+
throw new InstaboxError(`${e.name} grew while it was being uploaded`, { code: "file_changed" });
|
|
1022
|
+
}
|
|
1023
|
+
n += chunk.length;
|
|
1024
|
+
if (chunk.length) yield chunk;
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
if (n !== size) {
|
|
1028
|
+
throw new InstaboxError(`${e.name} shrank while it was being uploaded (${n} of ${size} bytes)`, {
|
|
1029
|
+
code: "file_changed"
|
|
1030
|
+
});
|
|
1031
|
+
}
|
|
1032
|
+
if (size % BLOCK) yield new Uint8Array(BLOCK - size % BLOCK);
|
|
1033
|
+
}
|
|
1034
|
+
yield new Uint8Array(BLOCK * 2);
|
|
1035
|
+
}
|
|
1036
|
+
var ByteReader = class {
|
|
1037
|
+
buf = new Uint8Array(0);
|
|
1038
|
+
it;
|
|
1039
|
+
done = false;
|
|
1040
|
+
constructor(src) {
|
|
1041
|
+
this.it = src[Symbol.asyncIterator]();
|
|
1042
|
+
}
|
|
1043
|
+
async fill() {
|
|
1044
|
+
if (this.done) return false;
|
|
1045
|
+
const r = await this.it.next();
|
|
1046
|
+
if (r.done) {
|
|
1047
|
+
this.done = true;
|
|
1048
|
+
return false;
|
|
1049
|
+
}
|
|
1050
|
+
const chunk = r.value instanceof Uint8Array ? r.value : new Uint8Array(r.value);
|
|
1051
|
+
if (this.buf.length === 0) this.buf = chunk;
|
|
1052
|
+
else {
|
|
1053
|
+
const b = new Uint8Array(this.buf.length + chunk.length);
|
|
1054
|
+
b.set(this.buf);
|
|
1055
|
+
b.set(chunk, this.buf.length);
|
|
1056
|
+
this.buf = b;
|
|
1057
|
+
}
|
|
1058
|
+
return true;
|
|
1059
|
+
}
|
|
1060
|
+
/** Exactly n bytes, or null at a clean end of input before any of them. */
|
|
1061
|
+
async exact(n) {
|
|
1062
|
+
while (this.buf.length < n) {
|
|
1063
|
+
if (!await this.fill()) {
|
|
1064
|
+
if (this.buf.length === 0) return null;
|
|
1065
|
+
throw truncated();
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
1068
|
+
const out = this.buf.subarray(0, n);
|
|
1069
|
+
this.buf = this.buf.subarray(n);
|
|
1070
|
+
return out;
|
|
1071
|
+
}
|
|
1072
|
+
/** n bytes as they arrive, in chunks. */
|
|
1073
|
+
async *chunks(n) {
|
|
1074
|
+
let left = n;
|
|
1075
|
+
while (left > 0) {
|
|
1076
|
+
if (this.buf.length === 0 && !await this.fill()) throw truncated();
|
|
1077
|
+
const take = Math.min(left, this.buf.length);
|
|
1078
|
+
const out = this.buf.subarray(0, take);
|
|
1079
|
+
this.buf = this.buf.subarray(take);
|
|
1080
|
+
left -= take;
|
|
1081
|
+
yield out;
|
|
1082
|
+
}
|
|
1083
|
+
}
|
|
1084
|
+
async skip(n) {
|
|
1085
|
+
for await (const _ of this.chunks(n)) void _;
|
|
1086
|
+
}
|
|
1087
|
+
};
|
|
1088
|
+
function truncated() {
|
|
1089
|
+
return new InstaboxError("the archive from the sandbox ended early", { code: "file_changed", retryable: true });
|
|
1090
|
+
}
|
|
1091
|
+
function invalidArchive(why) {
|
|
1092
|
+
return new InstaboxError(`the archive from the sandbox is not valid tar: ${why}`, { code: "invalid_response" });
|
|
1093
|
+
}
|
|
1094
|
+
function cstring(b) {
|
|
1095
|
+
const z = b.indexOf(0);
|
|
1096
|
+
return dec.decode(z < 0 ? b : b.subarray(0, z));
|
|
1097
|
+
}
|
|
1098
|
+
function number(b) {
|
|
1099
|
+
if (b[0] & 128) {
|
|
1100
|
+
let n = b[0] & 127;
|
|
1101
|
+
for (let i = 1; i < b.length; i++) n = n * 256 + b[i];
|
|
1102
|
+
return n;
|
|
1103
|
+
}
|
|
1104
|
+
const s = cstring(b).trim();
|
|
1105
|
+
if (s === "") return 0;
|
|
1106
|
+
if (!/^[0-7]+$/.test(s)) throw invalidArchive(`bad number ${JSON.stringify(s)}`);
|
|
1107
|
+
return parseInt(s, 8);
|
|
1108
|
+
}
|
|
1109
|
+
function parsePax(data) {
|
|
1110
|
+
const out = {};
|
|
1111
|
+
let off = 0;
|
|
1112
|
+
while (off < data.length) {
|
|
1113
|
+
const sp = data.indexOf(32, off);
|
|
1114
|
+
if (sp < 0) break;
|
|
1115
|
+
const len = parseInt(dec.decode(data.subarray(off, sp)), 10);
|
|
1116
|
+
if (!Number.isSafeInteger(len) || len <= 0 || off + len > data.length) throw invalidArchive("bad PAX record");
|
|
1117
|
+
const rec = dec.decode(data.subarray(sp + 1, off + len - 1));
|
|
1118
|
+
const eq = rec.indexOf("=");
|
|
1119
|
+
if (eq > 0) out[rec.slice(0, eq)] = rec.slice(eq + 1);
|
|
1120
|
+
off += len;
|
|
1121
|
+
}
|
|
1122
|
+
return out;
|
|
1123
|
+
}
|
|
1124
|
+
async function* untarStream(src) {
|
|
1125
|
+
const r = new ByteReader(src);
|
|
1126
|
+
let pax = {};
|
|
1127
|
+
let longName;
|
|
1128
|
+
let longLink;
|
|
1129
|
+
for (; ; ) {
|
|
1130
|
+
const h = await r.exact(BLOCK);
|
|
1131
|
+
if (h === null) return;
|
|
1132
|
+
if (h.every((b) => b === 0)) return;
|
|
1133
|
+
let sum = 0;
|
|
1134
|
+
for (let i = 0; i < BLOCK; i++) sum += i >= 148 && i < 156 ? 32 : h[i];
|
|
1135
|
+
if (sum !== number(h.subarray(148, 156))) throw invalidArchive("bad header checksum");
|
|
1136
|
+
const type = String.fromCharCode(h[156]);
|
|
1137
|
+
let size = number(h.subarray(124, 136));
|
|
1138
|
+
const magic = dec.decode(h.subarray(257, 263));
|
|
1139
|
+
let name = cstring(h.subarray(0, 100));
|
|
1140
|
+
if (magic === "ustar\0") {
|
|
1141
|
+
const prefix = cstring(h.subarray(345, 500));
|
|
1142
|
+
if (prefix) name = `${prefix}/${name}`;
|
|
1143
|
+
}
|
|
1144
|
+
let linkname = cstring(h.subarray(157, 257));
|
|
1145
|
+
const mode = number(h.subarray(100, 108)) & 4095;
|
|
1146
|
+
if (type === "x" || type === "g" || type === "L" || type === "K") {
|
|
1147
|
+
const data2 = await r.exact(size) ?? new Uint8Array(0);
|
|
1148
|
+
await r.skip((BLOCK - size % BLOCK) % BLOCK);
|
|
1149
|
+
if (type === "x") pax = { ...pax, ...parsePax(data2) };
|
|
1150
|
+
else if (type === "L") longName = cstring(data2);
|
|
1151
|
+
else if (type === "K") longLink = cstring(data2);
|
|
1152
|
+
continue;
|
|
1153
|
+
}
|
|
1154
|
+
if (pax.size !== void 0) size = Number(pax.size);
|
|
1155
|
+
name = pax.path ?? longName ?? name;
|
|
1156
|
+
linkname = pax.linkpath ?? longLink ?? linkname;
|
|
1157
|
+
pax = {};
|
|
1158
|
+
longName = longLink = void 0;
|
|
1159
|
+
if (!Number.isSafeInteger(size) || size < 0) throw invalidArchive("bad size");
|
|
1160
|
+
const kind = type === "0" || type === "\0" || type === "7" ? "file" : type === "5" ? "dir" : type === "2" ? "symlink" : type === "1" ? "link" : "other";
|
|
1161
|
+
const dataSize = kind === "file" || kind === "other" ? size : 0;
|
|
1162
|
+
let consumed = false;
|
|
1163
|
+
const data = {
|
|
1164
|
+
[Symbol.asyncIterator]: () => {
|
|
1165
|
+
consumed = true;
|
|
1166
|
+
return r.chunks(kind === "file" ? dataSize : 0);
|
|
1167
|
+
}
|
|
1168
|
+
};
|
|
1169
|
+
yield { name, type: kind, mode, size: kind === "file" ? size : 0, linkname, data };
|
|
1170
|
+
if (kind !== "file" || !consumed) await r.skip(dataSize);
|
|
1171
|
+
await r.skip((BLOCK - dataSize % BLOCK) % BLOCK);
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
|
|
1175
|
+
// src/local.ts
|
|
1176
|
+
function load() {
|
|
1177
|
+
return Promise.all([
|
|
1178
|
+
import("node:fs"),
|
|
1179
|
+
import("node:fs/promises"),
|
|
1180
|
+
import("node:path"),
|
|
1181
|
+
import("node:zlib"),
|
|
1182
|
+
import("node:stream"),
|
|
1183
|
+
import("node:stream/promises"),
|
|
1184
|
+
import("node:child_process")
|
|
1185
|
+
]).then(
|
|
1186
|
+
// A namespace import of a CommonJS built-in (node:stream) types differently from `typeof import`.
|
|
1187
|
+
([fs, fsp, path, zlib, stream, sp, cp]) => ({ fs, fsp, path, zlib, stream, sp, cp })
|
|
1188
|
+
);
|
|
1189
|
+
}
|
|
1190
|
+
var mods;
|
|
1191
|
+
function node() {
|
|
1192
|
+
const m = mods ??= load().catch((err) => {
|
|
1193
|
+
mods = void 0;
|
|
1194
|
+
throw new InstaboxError("files.upload and files.download need Node.js (or Bun or Deno) file system access", {
|
|
1195
|
+
code: "unsupported",
|
|
1196
|
+
cause: err
|
|
1197
|
+
});
|
|
1198
|
+
});
|
|
1199
|
+
return m;
|
|
1200
|
+
}
|
|
1201
|
+
function localError(err, what) {
|
|
1202
|
+
if (err instanceof InstaboxError) return err;
|
|
1203
|
+
const code = err?.code;
|
|
1204
|
+
const msg = err?.message ?? String(err);
|
|
1205
|
+
if (code === "ENOENT")
|
|
1206
|
+
return new InstaboxError(`${what}: no such file or directory`, { code: "local_not_found", cause: err });
|
|
1207
|
+
return new InstaboxError(`${what}: ${msg}`, { code: "local_io_error", cause: err });
|
|
1208
|
+
}
|
|
1209
|
+
function run(n, file, args) {
|
|
1210
|
+
return new Promise((resolve) => {
|
|
1211
|
+
n.cp.execFile(
|
|
1212
|
+
file,
|
|
1213
|
+
args,
|
|
1214
|
+
{ encoding: "buffer", maxBuffer: 256 * 1024 * 1024 },
|
|
1215
|
+
(err, stdout) => resolve({ ok: !err, stdout })
|
|
1216
|
+
);
|
|
1217
|
+
});
|
|
1218
|
+
}
|
|
1219
|
+
async function listLocal(n, dir, opts = {}) {
|
|
1220
|
+
if (opts.git !== false) {
|
|
1221
|
+
const inside = await run(n, "git", ["-C", dir, "rev-parse", "--is-inside-work-tree"]);
|
|
1222
|
+
if (inside.ok && inside.stdout.toString().trim() === "true") {
|
|
1223
|
+
const args = opts.all ? ["-C", dir, "ls-files", "-co", "--exclude-standard", "-z"] : ["-C", dir, "ls-files", "-c", "-z"];
|
|
1224
|
+
const ls = await run(n, "git", args);
|
|
1225
|
+
if (!ls.ok) throw new InstaboxError(`git ls-files failed in ${dir}`, { code: "local_io_error" });
|
|
1226
|
+
return { names: ls.stdout.toString("utf8").split("\0").filter(Boolean), git: true };
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
const names = [];
|
|
1230
|
+
const walk = async (rel) => {
|
|
1231
|
+
const abs = rel ? n.path.join(dir, rel) : dir;
|
|
1232
|
+
const ents = await n.fsp.readdir(abs, { withFileTypes: true });
|
|
1233
|
+
ents.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
|
|
1234
|
+
for (const e of ents) {
|
|
1235
|
+
const r = rel ? `${rel}/${e.name}` : e.name;
|
|
1236
|
+
names.push(r);
|
|
1237
|
+
if (e.isDirectory()) await walk(r);
|
|
1238
|
+
}
|
|
1239
|
+
};
|
|
1240
|
+
await walk("");
|
|
1241
|
+
return { names, git: false };
|
|
1242
|
+
}
|
|
1243
|
+
function packLocal(n, dir, names, counts) {
|
|
1244
|
+
async function* entries() {
|
|
1245
|
+
for (const rel of names) {
|
|
1246
|
+
const abs = n.path.join(dir, ...rel.split("/"));
|
|
1247
|
+
let st;
|
|
1248
|
+
try {
|
|
1249
|
+
st = await n.fsp.lstat(abs);
|
|
1250
|
+
} catch (err) {
|
|
1251
|
+
if (err.code === "ENOENT") continue;
|
|
1252
|
+
throw localError(err, abs);
|
|
1253
|
+
}
|
|
1254
|
+
const base = { name: rel, mode: st.mode & 4095, mtime: Math.floor(st.mtimeMs / 1e3) };
|
|
1255
|
+
if (st.isFile()) {
|
|
1256
|
+
counts.files++;
|
|
1257
|
+
yield {
|
|
1258
|
+
...base,
|
|
1259
|
+
type: "file",
|
|
1260
|
+
size: st.size,
|
|
1261
|
+
data: () => n.fs.createReadStream(abs, { highWaterMark: 256 * 1024 })
|
|
1262
|
+
};
|
|
1263
|
+
} else if (st.isDirectory()) yield { ...base, type: "dir" };
|
|
1264
|
+
else if (st.isSymbolicLink()) yield { ...base, type: "symlink", linkname: await n.fsp.readlink(abs) };
|
|
1265
|
+
}
|
|
1266
|
+
}
|
|
1267
|
+
const tar = n.stream.Readable.from(tarStream(entries()), { objectMode: false });
|
|
1268
|
+
const gz = n.zlib.createGzip();
|
|
1269
|
+
n.stream.pipeline(tar, gz, () => {
|
|
1270
|
+
});
|
|
1271
|
+
return gz;
|
|
1272
|
+
}
|
|
1273
|
+
function unsafe(name) {
|
|
1274
|
+
return new InstaboxError(`unsafe path ${JSON.stringify(name)} in the archive from the sandbox`, {
|
|
1275
|
+
code: "invalid_response"
|
|
1276
|
+
});
|
|
1277
|
+
}
|
|
1278
|
+
function components(name) {
|
|
1279
|
+
if (name.startsWith("/")) throw unsafe(name);
|
|
1280
|
+
const parts = [];
|
|
1281
|
+
for (const p of name.split("/")) {
|
|
1282
|
+
if (p === "" || p === ".") continue;
|
|
1283
|
+
if (p === ".." || p.includes("\\") || p.includes("\0")) throw unsafe(name);
|
|
1284
|
+
parts.push(p);
|
|
1285
|
+
}
|
|
1286
|
+
return parts;
|
|
1287
|
+
}
|
|
1288
|
+
async function unpackLocal(n, src, dest) {
|
|
1289
|
+
await n.fsp.mkdir(dest, { recursive: true });
|
|
1290
|
+
const root = await n.fsp.realpath(dest);
|
|
1291
|
+
const gunzip = n.zlib.createGunzip();
|
|
1292
|
+
n.stream.pipeline(n.stream.Readable.from(src, { objectMode: false }), gunzip, () => {
|
|
1293
|
+
});
|
|
1294
|
+
const dirModes = [];
|
|
1295
|
+
let files = 0;
|
|
1296
|
+
const ensureDir = async (parts, name) => {
|
|
1297
|
+
let cur = root;
|
|
1298
|
+
for (const p of parts) {
|
|
1299
|
+
cur = n.path.join(cur, p);
|
|
1300
|
+
let st;
|
|
1301
|
+
try {
|
|
1302
|
+
st = await n.fsp.lstat(cur);
|
|
1303
|
+
} catch (err) {
|
|
1304
|
+
if (err.code !== "ENOENT") throw err;
|
|
1305
|
+
}
|
|
1306
|
+
if (!st) await n.fsp.mkdir(cur, { mode: 493 });
|
|
1307
|
+
else if (!st.isDirectory()) throw unsafe(name);
|
|
1308
|
+
}
|
|
1309
|
+
return cur;
|
|
1310
|
+
};
|
|
1311
|
+
const clear = async (abs, name) => {
|
|
1312
|
+
let st;
|
|
1313
|
+
try {
|
|
1314
|
+
st = await n.fsp.lstat(abs);
|
|
1315
|
+
} catch {
|
|
1316
|
+
return;
|
|
1317
|
+
}
|
|
1318
|
+
if (st.isDirectory()) {
|
|
1319
|
+
throw new InstaboxError(`${name} is a directory locally; the archive has a file there`, {
|
|
1320
|
+
code: "local_io_error"
|
|
1321
|
+
});
|
|
1322
|
+
}
|
|
1323
|
+
await n.fsp.unlink(abs);
|
|
1324
|
+
};
|
|
1325
|
+
for await (const e of untarStream(gunzip)) {
|
|
1326
|
+
const parts = components(e.name);
|
|
1327
|
+
if (parts.length === 0) {
|
|
1328
|
+
for await (const _ of e.data) void _;
|
|
1329
|
+
continue;
|
|
1330
|
+
}
|
|
1331
|
+
const parent = await ensureDir(parts.slice(0, -1), e.name);
|
|
1332
|
+
const abs = n.path.join(parent, parts[parts.length - 1]);
|
|
1333
|
+
if (e.type === "dir") {
|
|
1334
|
+
await ensureDir(parts, e.name);
|
|
1335
|
+
dirModes.push([abs, e.mode]);
|
|
1336
|
+
} else if (e.type === "file") {
|
|
1337
|
+
await clear(abs, e.name);
|
|
1338
|
+
await n.sp.pipeline(
|
|
1339
|
+
n.stream.Readable.from(e.data, { objectMode: false }),
|
|
1340
|
+
n.fs.createWriteStream(abs, { flags: "wx", mode: e.mode | 128 })
|
|
1341
|
+
);
|
|
1342
|
+
await n.fsp.chmod(abs, e.mode);
|
|
1343
|
+
files++;
|
|
1344
|
+
} else if (e.type === "symlink") {
|
|
1345
|
+
await clear(abs, e.name);
|
|
1346
|
+
await n.fsp.symlink(e.linkname, abs);
|
|
1347
|
+
} else if (e.type === "link") {
|
|
1348
|
+
const tparts = components(e.linkname);
|
|
1349
|
+
const target = n.path.join(await ensureDir(tparts.slice(0, -1), e.linkname), tparts[tparts.length - 1] ?? "");
|
|
1350
|
+
const st = await n.fsp.lstat(target).catch(() => void 0);
|
|
1351
|
+
if (!st?.isFile()) throw unsafe(e.linkname);
|
|
1352
|
+
await clear(abs, e.name);
|
|
1353
|
+
await n.fsp.copyFile(target, abs);
|
|
1354
|
+
files++;
|
|
1355
|
+
}
|
|
1356
|
+
}
|
|
1357
|
+
for (const [abs, mode] of dirModes.reverse()) await n.fsp.chmod(abs, mode);
|
|
1358
|
+
return files;
|
|
1359
|
+
}
|
|
1360
|
+
|
|
833
1361
|
// src/files.ts
|
|
834
1362
|
var MAX_FILE_BYTES = 10 * 1024 * 1024;
|
|
1363
|
+
var MAX_UPLOAD_BYTES = 5 * 1024 * 1024 * 1024;
|
|
835
1364
|
var TRANSFER_TIMEOUT_MS = 3e5;
|
|
1365
|
+
var TRANSFER_MAX_MS = 72e5 + 12e4;
|
|
1366
|
+
var TRANSFER_IDLE_MS = 12e4;
|
|
1367
|
+
var TRANSFER_EXEC_MS = 6e5;
|
|
836
1368
|
var WRITE_CHUNK_B64 = 48 * 1024;
|
|
837
1369
|
var READ_CHUNK_BYTES = 512 * 1024;
|
|
1370
|
+
var PROBE_PATH = "instabox-sdk-route-probe";
|
|
838
1371
|
var Files = class {
|
|
839
1372
|
/** @internal */
|
|
840
1373
|
constructor(commands, http, sandboxId) {
|
|
@@ -848,22 +1381,45 @@ var Files = class {
|
|
|
848
1381
|
home;
|
|
849
1382
|
/** False once a server answered that it has no file routes. */
|
|
850
1383
|
routes = true;
|
|
1384
|
+
/** True once a server answered on a file route, so a stream need not probe for it. */
|
|
1385
|
+
routesSeen = false;
|
|
1386
|
+
get filesPath() {
|
|
1387
|
+
return `/v1/machines/${encodeURIComponent(this.sandboxId ?? "")}/files`;
|
|
1388
|
+
}
|
|
851
1389
|
async read(path, opts = {}) {
|
|
852
1390
|
const limit = opts.maxBytes ?? MAX_FILE_BYTES;
|
|
853
|
-
|
|
854
|
-
const
|
|
1391
|
+
if (!(limit >= 0)) throw new InstaboxError("maxBytes must be a number, at least 0", { code: "bad_request" });
|
|
1392
|
+
const res = await this.openRoute(path);
|
|
1393
|
+
const bytes = res ? await this.readRoute(res, path, limit) : await this.readExec(path, limit);
|
|
855
1394
|
return opts.format === "bytes" ? bytes : decodeUtf8(bytes);
|
|
856
1395
|
}
|
|
857
|
-
/**
|
|
858
|
-
|
|
1396
|
+
/**
|
|
1397
|
+
* Opens a file for reading as a stream, with no size cap: the bytes arrive as the server sends them,
|
|
1398
|
+
* so a file of any size reads in bounded memory. Errors before the first byte (`not_found`, a
|
|
1399
|
+
* directory) reject the promise; a stream cut short errors with `file_changed`. Read it with
|
|
1400
|
+
* `for await`, `getReader()`, or in Node `Readable.fromWeb(stream)` and `pipeline`. On a server
|
|
1401
|
+
* without the file routes the file is read over exec first (at most 10 MiB).
|
|
1402
|
+
*/
|
|
1403
|
+
async readStream(path, opts = {}) {
|
|
1404
|
+
const res = await this.openRoute(path, opts.signal);
|
|
1405
|
+
if (!res) return iterable(oneChunk(await this.readExec(path, MAX_FILE_BYTES)));
|
|
1406
|
+
return iterable(this.countedBody(res, path, opts.signal));
|
|
1407
|
+
}
|
|
1408
|
+
/**
|
|
1409
|
+
* `GET .../files/content` of `path` (or of `abs`, already absolute); undefined when the server has
|
|
1410
|
+
* no such route. `not_found` and `not_a_file` become `not_found`: a directory is not a file either.
|
|
1411
|
+
*/
|
|
1412
|
+
async openRoute(path, signal, abs) {
|
|
859
1413
|
if (!this.http || !this.sandboxId || !this.routes) return void 0;
|
|
860
|
-
|
|
861
|
-
let res;
|
|
1414
|
+
abs ??= await this.absolute(path);
|
|
862
1415
|
try {
|
|
863
|
-
res = await this.http.send("GET",
|
|
1416
|
+
const res = await this.http.send("GET", `${this.filesPath}/content`, {
|
|
864
1417
|
query: { path: abs },
|
|
865
|
-
timeoutMs: TRANSFER_TIMEOUT_MS
|
|
1418
|
+
timeoutMs: TRANSFER_TIMEOUT_MS,
|
|
1419
|
+
signal
|
|
866
1420
|
});
|
|
1421
|
+
this.routesSeen = true;
|
|
1422
|
+
return res;
|
|
867
1423
|
} catch (err) {
|
|
868
1424
|
if (routeMissing(err)) {
|
|
869
1425
|
this.routes = false;
|
|
@@ -879,19 +1435,72 @@ var Files = class {
|
|
|
879
1435
|
}
|
|
880
1436
|
throw err;
|
|
881
1437
|
}
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
1438
|
+
}
|
|
1439
|
+
/** Reads a whole response body of `path`, at most `limit` bytes. */
|
|
1440
|
+
async readRoute(res, path, limit) {
|
|
1441
|
+
try {
|
|
1442
|
+
const declared = Number(res.headers.get("Content-Length") ?? NaN);
|
|
1443
|
+
if (Number.isSafeInteger(declared) && declared > limit) {
|
|
1444
|
+
void res.body?.cancel().catch(() => {
|
|
1445
|
+
});
|
|
1446
|
+
throw new InstaboxError(`${path} is larger than the ${limit}-byte limit of files.read`, {
|
|
1447
|
+
code: "file_too_large"
|
|
1448
|
+
});
|
|
1449
|
+
}
|
|
1450
|
+
const bytes = await readBody(res, limit, path);
|
|
1451
|
+
if (Number.isSafeInteger(declared) && bytes.length !== declared) {
|
|
1452
|
+
throw new InstaboxError(`got ${bytes.length} of ${declared} bytes of ${path}`, { code: "file_changed" });
|
|
1453
|
+
}
|
|
1454
|
+
return bytes;
|
|
1455
|
+
} finally {
|
|
1456
|
+
this.http?.release(res);
|
|
893
1457
|
}
|
|
894
|
-
|
|
1458
|
+
}
|
|
1459
|
+
/** A response body as a stream that errors with `file_changed` when it ends short of Content-Length. */
|
|
1460
|
+
countedBody(res, path, signal) {
|
|
1461
|
+
const http = this.http;
|
|
1462
|
+
const declared = Number(res.headers.get("Content-Length") ?? NaN);
|
|
1463
|
+
const reader = res.body?.getReader();
|
|
1464
|
+
let n = 0;
|
|
1465
|
+
return new ReadableStream(
|
|
1466
|
+
{
|
|
1467
|
+
async pull(c) {
|
|
1468
|
+
if (!reader) {
|
|
1469
|
+
http.release(res);
|
|
1470
|
+
return c.close();
|
|
1471
|
+
}
|
|
1472
|
+
let r;
|
|
1473
|
+
try {
|
|
1474
|
+
r = await reader.read();
|
|
1475
|
+
} catch (err) {
|
|
1476
|
+
http.release(res);
|
|
1477
|
+
if (signal?.aborted) return c.error(new InstaboxError(`reading ${path} was aborted`, { code: "aborted" }));
|
|
1478
|
+
const msg = err?.message ?? String(err);
|
|
1479
|
+
return c.error(
|
|
1480
|
+
new InstaboxError(`reading ${path} stopped after ${n} bytes: ${msg}`, {
|
|
1481
|
+
code: "file_changed",
|
|
1482
|
+
retryable: true,
|
|
1483
|
+
cause: err
|
|
1484
|
+
})
|
|
1485
|
+
);
|
|
1486
|
+
}
|
|
1487
|
+
if (r.done) {
|
|
1488
|
+
http.release(res);
|
|
1489
|
+
if (Number.isSafeInteger(declared) && n !== declared) {
|
|
1490
|
+
return c.error(new InstaboxError(`got ${n} of ${declared} bytes of ${path}`, { code: "file_changed" }));
|
|
1491
|
+
}
|
|
1492
|
+
return c.close();
|
|
1493
|
+
}
|
|
1494
|
+
n += r.value.length;
|
|
1495
|
+
c.enqueue(r.value);
|
|
1496
|
+
},
|
|
1497
|
+
cancel(reason) {
|
|
1498
|
+
http.release(res);
|
|
1499
|
+
return reader?.cancel(reason);
|
|
1500
|
+
}
|
|
1501
|
+
},
|
|
1502
|
+
{ highWaterMark: 0 }
|
|
1503
|
+
);
|
|
895
1504
|
}
|
|
896
1505
|
async readExec(path, limit) {
|
|
897
1506
|
const p = arg(path);
|
|
@@ -924,57 +1533,201 @@ var Files = class {
|
|
|
924
1533
|
return bytes;
|
|
925
1534
|
}
|
|
926
1535
|
/**
|
|
927
|
-
* Writes a file, creating parent directories. Replaces the file atomically (temp file + rename)
|
|
928
|
-
* Throws `is_a_directory` when `path` is a directory.
|
|
1536
|
+
* Writes a file, creating parent directories. Replaces the file atomically (temp file + rename), so
|
|
1537
|
+
* a failed or aborted write leaves the old file. Throws `is_a_directory` when `path` is a directory.
|
|
1538
|
+
*
|
|
1539
|
+
* `data` is a string, bytes, or a stream (a Node `Readable`, a web `ReadableStream`, an
|
|
1540
|
+
* `AsyncIterable` of chunks): a stream is sent as it is read, in bounded memory, up to the server's
|
|
1541
|
+
* 5 GiB. The size and SHA-256 the server reports are checked against what was sent
|
|
1542
|
+
* (`transfer_mismatch` when they differ). On a server without the file routes, writes go over exec
|
|
1543
|
+
* and are capped at 10 MiB (`file_too_large`).
|
|
929
1544
|
*/
|
|
930
|
-
async write(path, data) {
|
|
931
|
-
const bytes =
|
|
932
|
-
if (bytes
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
1545
|
+
async write(path, data, opts = {}) {
|
|
1546
|
+
const bytes = asBytes(data);
|
|
1547
|
+
if (bytes) {
|
|
1548
|
+
if (await this.writeRoute(path, bytes, opts.signal)) return { path };
|
|
1549
|
+
if (bytes.length > MAX_FILE_BYTES) throw tooLargeForExec();
|
|
1550
|
+
await this.writeExec(path, bytes);
|
|
1551
|
+
return { path };
|
|
1552
|
+
}
|
|
1553
|
+
const src = asIterable(data);
|
|
1554
|
+
if (await this.routesAvailable(opts.signal)) {
|
|
1555
|
+
if (await this.writeRoute(path, src, opts.signal)) return { path };
|
|
1556
|
+
throw noRoutes();
|
|
936
1557
|
}
|
|
937
|
-
|
|
938
|
-
await this.writeExec(path, bytes);
|
|
1558
|
+
await this.writeExec(path, await collect(src, MAX_FILE_BYTES));
|
|
939
1559
|
return { path };
|
|
940
1560
|
}
|
|
941
1561
|
/**
|
|
942
1562
|
* Writes over `PUT .../files?parents=true`, which writes a temp file beside the target and renames
|
|
943
1563
|
* it into place once every byte arrived. False when the server has no such route.
|
|
944
1564
|
*/
|
|
945
|
-
async
|
|
1565
|
+
async writeRoute(path, body, signal) {
|
|
946
1566
|
if (!this.http || !this.sandboxId || !this.routes) return false;
|
|
947
1567
|
const abs = await this.absolute(path);
|
|
948
|
-
let res;
|
|
949
1568
|
try {
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
1569
|
+
return await this.put(abs, body, { parents: "true" }, signal) !== void 0;
|
|
1570
|
+
} catch (err) {
|
|
1571
|
+
if (err instanceof InstaboxError && err.code === "not_a_file") {
|
|
1572
|
+
const dir = await this.commands.exec(`test -d ${arg(path)}`).catch(() => void 0);
|
|
1573
|
+
if (dir?.exitCode === 0) {
|
|
1574
|
+
throw new InstaboxError(`is a directory: ${path}`, { status: 409, code: "is_a_directory", cause: err });
|
|
1575
|
+
}
|
|
1576
|
+
}
|
|
1577
|
+
throw err;
|
|
1578
|
+
}
|
|
1579
|
+
}
|
|
1580
|
+
/**
|
|
1581
|
+
* True when the server has the file routes. A stream can be sent only once, so before the first one
|
|
1582
|
+
* the route is probed with a relative path, which the server refuses (400) before touching the
|
|
1583
|
+
* sandbox; a server without the route answers 404 or 405.
|
|
1584
|
+
*/
|
|
1585
|
+
async routesAvailable(signal) {
|
|
1586
|
+
if (!this.http || !this.sandboxId || !this.routes) return false;
|
|
1587
|
+
if (this.routesSeen) return true;
|
|
1588
|
+
try {
|
|
1589
|
+
await this.http.request("PUT", this.filesPath, {
|
|
1590
|
+
query: { path: PROBE_PATH },
|
|
1591
|
+
rawBody: new Uint8Array(0),
|
|
953
1592
|
idempotent: false,
|
|
954
1593
|
retry: true,
|
|
955
|
-
|
|
1594
|
+
signal
|
|
956
1595
|
});
|
|
957
1596
|
} catch (err) {
|
|
958
1597
|
if (routeMissing(err)) {
|
|
959
1598
|
this.routes = false;
|
|
960
1599
|
return false;
|
|
961
1600
|
}
|
|
962
|
-
if (err instanceof InstaboxError
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
1601
|
+
if (!(err instanceof InstaboxError) || err.status !== 400) throw err;
|
|
1602
|
+
}
|
|
1603
|
+
this.routesSeen = true;
|
|
1604
|
+
return true;
|
|
1605
|
+
}
|
|
1606
|
+
/**
|
|
1607
|
+
* `PUT .../files` of `body` to the absolute path `abs`, checking the size and SHA-256 the server
|
|
1608
|
+
* reports. Bytes are retried on 502-504 (the server replaces the file atomically, so a repeat writes
|
|
1609
|
+
* the same bytes); a stream is sent once, as it is read, and given up when it moves nothing for
|
|
1610
|
+
* 2 minutes. Undefined when the server has no such route.
|
|
1611
|
+
*/
|
|
1612
|
+
async put(abs, body, query, signal) {
|
|
1613
|
+
if (!this.http || !this.sandboxId || !this.routes) return void 0;
|
|
1614
|
+
let res;
|
|
1615
|
+
let sent;
|
|
1616
|
+
let want;
|
|
1617
|
+
if (body instanceof Uint8Array) {
|
|
1618
|
+
try {
|
|
1619
|
+
res = await this.http.request("PUT", this.filesPath, {
|
|
1620
|
+
query: { path: abs, ...query },
|
|
1621
|
+
rawBody: body,
|
|
1622
|
+
idempotent: false,
|
|
1623
|
+
retry: true,
|
|
1624
|
+
timeoutMs: bufferedTimeout(body.length),
|
|
1625
|
+
signal
|
|
1626
|
+
});
|
|
1627
|
+
} catch (err) {
|
|
1628
|
+
if (routeMissing(err)) {
|
|
1629
|
+
this.routes = false;
|
|
1630
|
+
return void 0;
|
|
966
1631
|
}
|
|
1632
|
+
throw err;
|
|
967
1633
|
}
|
|
968
|
-
|
|
1634
|
+
sent = body.length;
|
|
1635
|
+
want = await sha256Hex(body);
|
|
1636
|
+
} else {
|
|
1637
|
+
const up = await this.putStream(abs, body, query, signal);
|
|
1638
|
+
if (!up) return void 0;
|
|
1639
|
+
({ res, sent, want } = up);
|
|
969
1640
|
}
|
|
970
|
-
|
|
971
|
-
if (res?.size !==
|
|
1641
|
+
this.routesSeen = true;
|
|
1642
|
+
if (res?.size !== sent || want !== void 0 && res.sha256 !== want) {
|
|
972
1643
|
throw new InstaboxError(
|
|
973
|
-
`the sandbox received ${res?.size} bytes with sha256 ${res?.sha256}; sent ${
|
|
1644
|
+
`the sandbox received ${res?.size} bytes with sha256 ${res?.sha256}; sent ${sent} with ${want}`,
|
|
974
1645
|
{ code: "transfer_mismatch" }
|
|
975
1646
|
);
|
|
976
1647
|
}
|
|
977
|
-
return
|
|
1648
|
+
return { size: sent };
|
|
1649
|
+
}
|
|
1650
|
+
async putStream(abs, src, query, signal) {
|
|
1651
|
+
const hash = await sha256Stream();
|
|
1652
|
+
const ctrl = new AbortController();
|
|
1653
|
+
let idle;
|
|
1654
|
+
let idleFired = false;
|
|
1655
|
+
const touch = () => {
|
|
1656
|
+
clearTimeout(idle);
|
|
1657
|
+
idle = setTimeout(() => {
|
|
1658
|
+
idleFired = true;
|
|
1659
|
+
ctrl.abort();
|
|
1660
|
+
}, TRANSFER_IDLE_MS);
|
|
1661
|
+
};
|
|
1662
|
+
const onAbort = () => ctrl.abort();
|
|
1663
|
+
if (signal?.aborted) ctrl.abort();
|
|
1664
|
+
else signal?.addEventListener("abort", onAbort, { once: true });
|
|
1665
|
+
const it = src[Symbol.asyncIterator]();
|
|
1666
|
+
let sent = 0;
|
|
1667
|
+
let srcErr;
|
|
1668
|
+
const stream = new ReadableStream(
|
|
1669
|
+
{
|
|
1670
|
+
async pull(c) {
|
|
1671
|
+
touch();
|
|
1672
|
+
let r;
|
|
1673
|
+
try {
|
|
1674
|
+
r = await it.next();
|
|
1675
|
+
if (!r.done) {
|
|
1676
|
+
const b = chunkBytes(r.value);
|
|
1677
|
+
sent += b.length;
|
|
1678
|
+
if (sent > MAX_UPLOAD_BYTES) {
|
|
1679
|
+
throw new InstaboxError(`data is larger than the ${MAX_UPLOAD_BYTES}-byte limit of files.write`, {
|
|
1680
|
+
status: 413,
|
|
1681
|
+
code: "too_large"
|
|
1682
|
+
});
|
|
1683
|
+
}
|
|
1684
|
+
hash?.update(b);
|
|
1685
|
+
if (b.length) c.enqueue(b);
|
|
1686
|
+
return;
|
|
1687
|
+
}
|
|
1688
|
+
} catch (err) {
|
|
1689
|
+
clearTimeout(idle);
|
|
1690
|
+
srcErr = sourceError(err);
|
|
1691
|
+
throw srcErr;
|
|
1692
|
+
}
|
|
1693
|
+
clearTimeout(idle);
|
|
1694
|
+
c.close();
|
|
1695
|
+
},
|
|
1696
|
+
async cancel() {
|
|
1697
|
+
clearTimeout(idle);
|
|
1698
|
+
await it.return?.();
|
|
1699
|
+
}
|
|
1700
|
+
},
|
|
1701
|
+
{ highWaterMark: 0 }
|
|
1702
|
+
);
|
|
1703
|
+
try {
|
|
1704
|
+
const res = await this.http.request("PUT", this.filesPath, {
|
|
1705
|
+
query: { path: abs, ...query },
|
|
1706
|
+
streamBody: stream,
|
|
1707
|
+
idempotent: false,
|
|
1708
|
+
timeoutMs: TRANSFER_MAX_MS,
|
|
1709
|
+
signal: ctrl.signal
|
|
1710
|
+
});
|
|
1711
|
+
return { res, sent, want: hash?.digest("hex") };
|
|
1712
|
+
} catch (err) {
|
|
1713
|
+
if (srcErr) throw srcErr;
|
|
1714
|
+
if (idleFired) {
|
|
1715
|
+
throw new InstaboxTimeoutError(`the upload to ${abs} moved nothing for ${TRANSFER_IDLE_MS / 1e3} s`, {
|
|
1716
|
+
code: "request_timeout",
|
|
1717
|
+
cause: err
|
|
1718
|
+
});
|
|
1719
|
+
}
|
|
1720
|
+
if (routeMissing(err)) {
|
|
1721
|
+
this.routes = false;
|
|
1722
|
+
return void 0;
|
|
1723
|
+
}
|
|
1724
|
+
throw err;
|
|
1725
|
+
} finally {
|
|
1726
|
+
clearTimeout(idle);
|
|
1727
|
+
signal?.removeEventListener("abort", onAbort);
|
|
1728
|
+
void it.return?.()?.catch?.(() => {
|
|
1729
|
+
});
|
|
1730
|
+
}
|
|
978
1731
|
}
|
|
979
1732
|
async writeExec(path, bytes) {
|
|
980
1733
|
const p = arg(path);
|
|
@@ -999,6 +1752,172 @@ var Files = class {
|
|
|
999
1752
|
throw err;
|
|
1000
1753
|
}
|
|
1001
1754
|
}
|
|
1755
|
+
/**
|
|
1756
|
+
* Puts `src` at the absolute temporary path `abs` (mode 0600): over the file route, or in base64
|
|
1757
|
+
* chunks over exec (`instabox push`'s fallback) on a server without it.
|
|
1758
|
+
*/
|
|
1759
|
+
async putTemp(abs, src, signal) {
|
|
1760
|
+
const replayable = src instanceof Uint8Array;
|
|
1761
|
+
if (replayable || await this.routesAvailable(signal)) {
|
|
1762
|
+
if (await this.put(abs, src, { mode: "0600" }, signal)) return;
|
|
1763
|
+
if (!replayable) throw noRoutes();
|
|
1764
|
+
}
|
|
1765
|
+
let first = true;
|
|
1766
|
+
for await (const chunk of rechunk(replayable ? [src] : src, EXEC_CHUNK_BYTES)) {
|
|
1767
|
+
if (signal?.aborted) throw new InstaboxError("the transfer was aborted", { code: "aborted" });
|
|
1768
|
+
await this.transferExec(PUSH_CHUNK_SCRIPT, { IB_TMP: abs, IB_FIRST: first ? "1" : "0" }, "", signal, {
|
|
1769
|
+
stdin: bytesToBase64(chunk)
|
|
1770
|
+
});
|
|
1771
|
+
first = false;
|
|
1772
|
+
}
|
|
1773
|
+
if (first) await this.transferExec(PUSH_CHUNK_SCRIPT, { IB_TMP: abs, IB_FIRST: "1" }, "", signal, { stdin: "" });
|
|
1774
|
+
}
|
|
1775
|
+
/**
|
|
1776
|
+
* Runs a transfer script and returns its stdout after `mark`. A non-zero exit throws `transfer_failed`
|
|
1777
|
+
* (`permission_denied`, status 403, when the sandbox refused access), as the CLI reports it.
|
|
1778
|
+
*/
|
|
1779
|
+
async transferExec(cmd, envs, mark, signal, extra = {}) {
|
|
1780
|
+
const r = await this.commands.exec(cmd, { envs, timeoutMs: TRANSFER_EXEC_MS, signal, stdin: extra.stdin });
|
|
1781
|
+
if (r.timedOut) {
|
|
1782
|
+
throw new InstaboxTimeoutError(`the transfer timed out after ${TRANSFER_EXEC_MS / 1e3} s in the sandbox`, {
|
|
1783
|
+
code: "request_timeout"
|
|
1784
|
+
});
|
|
1785
|
+
}
|
|
1786
|
+
if (r.exitCode !== 0) {
|
|
1787
|
+
const msg = r.stderr.trim() || `exit status ${r.exitCode}`;
|
|
1788
|
+
if (/Permission denied|Operation not permitted/.test(msg)) {
|
|
1789
|
+
throw new InstaboxError(`in the sandbox: ${msg}`, { status: 403, code: "permission_denied" });
|
|
1790
|
+
}
|
|
1791
|
+
throw new InstaboxError(`in the sandbox: ${msg}`, { code: "transfer_failed" });
|
|
1792
|
+
}
|
|
1793
|
+
if (!mark) return "";
|
|
1794
|
+
const i = r.stdout.indexOf(mark);
|
|
1795
|
+
if (i < 0 || r.truncated)
|
|
1796
|
+
throw new InstaboxError("unexpected output from the sandbox", { code: "invalid_response" });
|
|
1797
|
+
return r.stdout.slice(i + mark.length);
|
|
1798
|
+
}
|
|
1799
|
+
/**
|
|
1800
|
+
* Uploads a local directory's contents into `remoteDir` in one call, as one gzipped tar, the way
|
|
1801
|
+
* `instabox push` does: streamed over `PUT .../files` to a temporary file, then unpacked in the
|
|
1802
|
+
* sandbox with `tar`. `remoteDir` and its parents are created; existing files there are replaced,
|
|
1803
|
+
* others kept. In a git work tree only what git tracks is uploaded (pass `all: true` to add
|
|
1804
|
+
* untracked files git does not ignore, `git: false` to upload everything). Symlinks are uploaded as
|
|
1805
|
+
* symlinks, never followed; sockets, FIFOs and devices are skipped. Node.js (or Bun, Deno) only.
|
|
1806
|
+
*/
|
|
1807
|
+
async upload(localDir, remoteDir, opts = {}) {
|
|
1808
|
+
const n = await node();
|
|
1809
|
+
const st = await n.fsp.stat(localDir).catch((err) => {
|
|
1810
|
+
throw localError(err, localDir);
|
|
1811
|
+
});
|
|
1812
|
+
if (!st.isDirectory()) {
|
|
1813
|
+
throw new InstaboxError(`${localDir} is not a directory; write a single file with files.write`, {
|
|
1814
|
+
code: "not_a_directory"
|
|
1815
|
+
});
|
|
1816
|
+
}
|
|
1817
|
+
const { names } = await listLocal(n, localDir, opts).catch((err) => {
|
|
1818
|
+
throw localError(err, localDir);
|
|
1819
|
+
});
|
|
1820
|
+
const counts = { files: 0 };
|
|
1821
|
+
let bytes = 0;
|
|
1822
|
+
const packed = packLocal(n, localDir, names, counts);
|
|
1823
|
+
async function* counted() {
|
|
1824
|
+
try {
|
|
1825
|
+
for await (const chunk of packed) {
|
|
1826
|
+
bytes += chunk.length;
|
|
1827
|
+
yield chunk;
|
|
1828
|
+
}
|
|
1829
|
+
} catch (err) {
|
|
1830
|
+
throw localError(err, localDir);
|
|
1831
|
+
}
|
|
1832
|
+
}
|
|
1833
|
+
const tmp = TRANSFER_TMP_PREFIX + randomHex();
|
|
1834
|
+
try {
|
|
1835
|
+
await this.putTemp(tmp, counted(), opts.signal);
|
|
1836
|
+
const out = await this.transferExec(
|
|
1837
|
+
PUSH_FINISH_SCRIPT,
|
|
1838
|
+
{ IB_TMP: tmp, IB_DEST: remoteDir },
|
|
1839
|
+
PUSH_MARK,
|
|
1840
|
+
opts.signal
|
|
1841
|
+
);
|
|
1842
|
+
const f = out.split("\0");
|
|
1843
|
+
if (f[0] !== "ok" || !f[1])
|
|
1844
|
+
throw new InstaboxError("unexpected output from the sandbox", { code: "invalid_response" });
|
|
1845
|
+
return { path: f[1], files: counts.files, bytes };
|
|
1846
|
+
} catch (err) {
|
|
1847
|
+
await this.commands.exec(`rm -f -- ${shellQuote(tmp)}`).catch(() => {
|
|
1848
|
+
});
|
|
1849
|
+
throw err;
|
|
1850
|
+
}
|
|
1851
|
+
}
|
|
1852
|
+
/**
|
|
1853
|
+
* Downloads a sandbox directory into `localDir` in one call, as one gzipped tar, the way
|
|
1854
|
+
* `instabox pull` packs it: `tar` in the sandbox (as root when sudo allows, as the file routes read),
|
|
1855
|
+
* streamed back over `GET .../files/content` and unpacked as it arrives. `localDir` and its parents
|
|
1856
|
+
* are created; existing files are replaced, others kept. Everything under `remoteDir` comes, dot
|
|
1857
|
+
* files and empty directories included; symlinks arrive as symlinks. No entry can write outside
|
|
1858
|
+
* `localDir`. Node.js (or Bun, Deno) only.
|
|
1859
|
+
*/
|
|
1860
|
+
async download(remoteDir, localDir, opts = {}) {
|
|
1861
|
+
const n = await node();
|
|
1862
|
+
const tmp = TRANSFER_TMP_PREFIX + randomHex();
|
|
1863
|
+
const envs = { IB_PATH: remoteDir };
|
|
1864
|
+
const f = (await this.transferExec(pullStartCmd(tmp), envs, PULL_MARK, opts.signal)).split("\0");
|
|
1865
|
+
if (f[0] === "missing") {
|
|
1866
|
+
throw new InstaboxError(`directory not found: ${remoteDir}`, { status: 404, code: "not_found" });
|
|
1867
|
+
}
|
|
1868
|
+
if (f[0] === "not_a_dir") {
|
|
1869
|
+
throw new InstaboxError(`${f[1]} is not a directory; read a single file with files.read or files.readStream`, {
|
|
1870
|
+
code: "not_a_directory"
|
|
1871
|
+
});
|
|
1872
|
+
}
|
|
1873
|
+
const size = Number(f[2]);
|
|
1874
|
+
if (f[0] !== "dir" || !f[1] || !Number.isSafeInteger(size) || size < 0) {
|
|
1875
|
+
throw new InstaboxError("unexpected output from the sandbox", { code: "invalid_response" });
|
|
1876
|
+
}
|
|
1877
|
+
try {
|
|
1878
|
+
let bytes = 0;
|
|
1879
|
+
const src = this.fetchTemp(tmp, size, envs, opts.signal);
|
|
1880
|
+
async function* counted() {
|
|
1881
|
+
for await (const chunk of src) {
|
|
1882
|
+
bytes += chunk.length;
|
|
1883
|
+
yield chunk;
|
|
1884
|
+
}
|
|
1885
|
+
}
|
|
1886
|
+
const files = await unpackLocal(n, counted(), localDir).catch((err) => {
|
|
1887
|
+
throw localError(err, localDir);
|
|
1888
|
+
});
|
|
1889
|
+
if (bytes !== size) {
|
|
1890
|
+
throw new InstaboxError(`got ${bytes} of ${size} bytes of the archive`, { code: "file_changed" });
|
|
1891
|
+
}
|
|
1892
|
+
return { path: localDir, remotePath: f[1], files, bytes };
|
|
1893
|
+
} finally {
|
|
1894
|
+
await this.commands.exec(pullRemoveCmd(tmp), { envs }).catch(() => {
|
|
1895
|
+
});
|
|
1896
|
+
}
|
|
1897
|
+
}
|
|
1898
|
+
/** The temporary archive's bytes: over the file route, or in base64 chunks over exec without it. */
|
|
1899
|
+
async *fetchTemp(tmp, size, envs, signal) {
|
|
1900
|
+
const res = await this.openRoute(tmp, signal, tmp);
|
|
1901
|
+
if (res) {
|
|
1902
|
+
yield* iterable(this.countedBody(res, tmp, signal));
|
|
1903
|
+
return;
|
|
1904
|
+
}
|
|
1905
|
+
for (let off = 0; off < size; off += EXEC_CHUNK_BYTES) {
|
|
1906
|
+
const want = Math.min(EXEC_CHUNK_BYTES, size - off);
|
|
1907
|
+
const b = base64ToBytes(await this.transferExec(pullChunkCmd(tmp, off, want), envs, PULL_MARK, signal));
|
|
1908
|
+
if (b.length !== want) throw new InstaboxError("the archive changed while reading it", { code: "file_changed" });
|
|
1909
|
+
yield b;
|
|
1910
|
+
}
|
|
1911
|
+
}
|
|
1912
|
+
/**
|
|
1913
|
+
* @internal Stages bytes as a temporary file for a command's stdin (`instabox exec --stdin`'s way) and
|
|
1914
|
+
* returns its path. The command removes it as it starts.
|
|
1915
|
+
*/
|
|
1916
|
+
async stageStdin(bytes, signal) {
|
|
1917
|
+
const p = STDIN_TMP_PREFIX + randomHex();
|
|
1918
|
+
await this.putTemp(p, bytes, signal);
|
|
1919
|
+
return p;
|
|
1920
|
+
}
|
|
1002
1921
|
/** The file routes take absolute paths; a relative one is relative to exec's working directory (HOME). */
|
|
1003
1922
|
async absolute(path) {
|
|
1004
1923
|
if (path.startsWith("/")) return path;
|
|
@@ -1044,6 +1963,121 @@ var Files = class {
|
|
|
1044
1963
|
function arg(path) {
|
|
1045
1964
|
return shellQuote(path.startsWith("-") ? `./${path}` : path);
|
|
1046
1965
|
}
|
|
1966
|
+
function tooLargeForExec() {
|
|
1967
|
+
return new InstaboxError(
|
|
1968
|
+
`data is larger than the ${MAX_FILE_BYTES}-byte limit of files.write on a server without the file routes`,
|
|
1969
|
+
{ code: "file_too_large" }
|
|
1970
|
+
);
|
|
1971
|
+
}
|
|
1972
|
+
function noRoutes() {
|
|
1973
|
+
return new InstaboxError("this server has no file routes (PUT /v1/machines/{id}/files) to stream to", {
|
|
1974
|
+
status: 404,
|
|
1975
|
+
code: "unsupported"
|
|
1976
|
+
});
|
|
1977
|
+
}
|
|
1978
|
+
function bufferedTimeout(size) {
|
|
1979
|
+
return Math.min(TRANSFER_MAX_MS, Math.max(TRANSFER_TIMEOUT_MS, Math.ceil(size / 65536) * 1e3));
|
|
1980
|
+
}
|
|
1981
|
+
function asBytes(data) {
|
|
1982
|
+
if (typeof data === "string") return new TextEncoder().encode(data);
|
|
1983
|
+
if (data instanceof Uint8Array) return data;
|
|
1984
|
+
if (data instanceof ArrayBuffer) return new Uint8Array(data);
|
|
1985
|
+
return void 0;
|
|
1986
|
+
}
|
|
1987
|
+
function asIterable(data) {
|
|
1988
|
+
const d = data;
|
|
1989
|
+
if (d && typeof d[Symbol.asyncIterator] === "function") return data;
|
|
1990
|
+
if (d && typeof d.getReader === "function") return iterable(data);
|
|
1991
|
+
throw new InstaboxError(
|
|
1992
|
+
"files.write takes a string, a Uint8Array, an ArrayBuffer, a ReadableStream or an AsyncIterable of chunks",
|
|
1993
|
+
{ code: "bad_request" }
|
|
1994
|
+
);
|
|
1995
|
+
}
|
|
1996
|
+
function chunkBytes(chunk) {
|
|
1997
|
+
if (chunk instanceof Uint8Array) return chunk;
|
|
1998
|
+
if (typeof chunk === "string") return new TextEncoder().encode(chunk);
|
|
1999
|
+
if (chunk instanceof ArrayBuffer) return new Uint8Array(chunk);
|
|
2000
|
+
throw new InstaboxError("a stream given to files.write yielded something other than bytes or a string", {
|
|
2001
|
+
code: "bad_request"
|
|
2002
|
+
});
|
|
2003
|
+
}
|
|
2004
|
+
function sourceError(err) {
|
|
2005
|
+
if (err instanceof InstaboxError) return err;
|
|
2006
|
+
const msg = err?.message ?? String(err);
|
|
2007
|
+
return new InstaboxError(`reading the data to write failed: ${msg}`, { code: "source_error", cause: err });
|
|
2008
|
+
}
|
|
2009
|
+
async function collect(src, limit) {
|
|
2010
|
+
const parts = [];
|
|
2011
|
+
let n = 0;
|
|
2012
|
+
try {
|
|
2013
|
+
for await (const c of src) {
|
|
2014
|
+
const b = chunkBytes(c);
|
|
2015
|
+
n += b.length;
|
|
2016
|
+
if (n > limit) throw tooLargeForExec();
|
|
2017
|
+
parts.push(b);
|
|
2018
|
+
}
|
|
2019
|
+
} catch (err) {
|
|
2020
|
+
throw sourceError(err);
|
|
2021
|
+
}
|
|
2022
|
+
return concat(parts, n);
|
|
2023
|
+
}
|
|
2024
|
+
function concat(parts, n) {
|
|
2025
|
+
const out = new Uint8Array(n);
|
|
2026
|
+
let off = 0;
|
|
2027
|
+
for (const p of parts) {
|
|
2028
|
+
out.set(p, off);
|
|
2029
|
+
off += p.length;
|
|
2030
|
+
}
|
|
2031
|
+
return out;
|
|
2032
|
+
}
|
|
2033
|
+
async function* rechunk(src, size) {
|
|
2034
|
+
let buf = new Uint8Array(size);
|
|
2035
|
+
let n = 0;
|
|
2036
|
+
for await (const c of src) {
|
|
2037
|
+
let b = chunkBytes(c);
|
|
2038
|
+
while (b.length) {
|
|
2039
|
+
const take = Math.min(size - n, b.length);
|
|
2040
|
+
buf.set(b.subarray(0, take), n);
|
|
2041
|
+
n += take;
|
|
2042
|
+
b = b.subarray(take);
|
|
2043
|
+
if (n === size) {
|
|
2044
|
+
yield buf;
|
|
2045
|
+
buf = new Uint8Array(size);
|
|
2046
|
+
n = 0;
|
|
2047
|
+
}
|
|
2048
|
+
}
|
|
2049
|
+
}
|
|
2050
|
+
if (n) yield buf.subarray(0, n);
|
|
2051
|
+
}
|
|
2052
|
+
function oneChunk(bytes) {
|
|
2053
|
+
return new ReadableStream({
|
|
2054
|
+
start(c) {
|
|
2055
|
+
if (bytes.length) c.enqueue(bytes);
|
|
2056
|
+
c.close();
|
|
2057
|
+
}
|
|
2058
|
+
});
|
|
2059
|
+
}
|
|
2060
|
+
function iterable(stream) {
|
|
2061
|
+
const s = stream;
|
|
2062
|
+
if (typeof s[Symbol.asyncIterator] !== "function") {
|
|
2063
|
+
Object.defineProperty(s, Symbol.asyncIterator, {
|
|
2064
|
+
configurable: true,
|
|
2065
|
+
value: async function* () {
|
|
2066
|
+
const reader = stream.getReader();
|
|
2067
|
+
try {
|
|
2068
|
+
for (; ; ) {
|
|
2069
|
+
const { done, value } = await reader.read();
|
|
2070
|
+
if (done) return;
|
|
2071
|
+
yield value;
|
|
2072
|
+
}
|
|
2073
|
+
} finally {
|
|
2074
|
+
reader.releaseLock();
|
|
2075
|
+
}
|
|
2076
|
+
}
|
|
2077
|
+
});
|
|
2078
|
+
}
|
|
2079
|
+
return s;
|
|
2080
|
+
}
|
|
1047
2081
|
async function readBody(res, limit, path) {
|
|
1048
2082
|
const tooLarge = () => new InstaboxError(`${path} is larger than the ${limit}-byte limit of files.read`, { code: "file_too_large" });
|
|
1049
2083
|
const reader = res.body?.getReader();
|
|
@@ -1070,13 +2104,7 @@ async function readBody(res, limit, path) {
|
|
|
1070
2104
|
cause: err
|
|
1071
2105
|
});
|
|
1072
2106
|
}
|
|
1073
|
-
|
|
1074
|
-
let off = 0;
|
|
1075
|
-
for (const c of chunks) {
|
|
1076
|
-
out.set(c, off);
|
|
1077
|
-
off += c.length;
|
|
1078
|
-
}
|
|
1079
|
-
return out;
|
|
2107
|
+
return concat(chunks, n);
|
|
1080
2108
|
}
|
|
1081
2109
|
function routeMissing(err) {
|
|
1082
2110
|
if (!(err instanceof InstaboxError)) return false;
|
|
@@ -1089,6 +2117,14 @@ async function sha256Hex(bytes) {
|
|
|
1089
2117
|
const d = new Uint8Array(await subtle.digest("SHA-256", bytes));
|
|
1090
2118
|
return Array.from(d, (x) => x.toString(16).padStart(2, "0")).join("");
|
|
1091
2119
|
}
|
|
2120
|
+
async function sha256Stream() {
|
|
2121
|
+
try {
|
|
2122
|
+
const c = await import("node:crypto");
|
|
2123
|
+
return c.createHash("sha256");
|
|
2124
|
+
} catch {
|
|
2125
|
+
return void 0;
|
|
2126
|
+
}
|
|
2127
|
+
}
|
|
1092
2128
|
function writeError(result, path) {
|
|
1093
2129
|
if (result.exitCode === 21) return new InstaboxError(`is a directory: ${path}`, { code: "is_a_directory" });
|
|
1094
2130
|
return new CommandExitError(result);
|
|
@@ -1175,30 +2211,33 @@ var HttpClient = class {
|
|
|
1175
2211
|
async send(method, path, opts = {}) {
|
|
1176
2212
|
const isRead = method === "GET" || method === "HEAD";
|
|
1177
2213
|
const idempotent = opts.idempotent ?? !isRead;
|
|
1178
|
-
const retry = opts.retry ?? (isRead || idempotent);
|
|
1179
|
-
const
|
|
2214
|
+
const retry = opts.streamBody ? false : opts.retry ?? (isRead || idempotent);
|
|
2215
|
+
const headers2 = {
|
|
1180
2216
|
"X-API-Key": this.#apiKey,
|
|
1181
2217
|
Accept: opts.accept ?? "application/json",
|
|
1182
2218
|
...opts.headers
|
|
1183
2219
|
};
|
|
1184
|
-
if (idempotent)
|
|
2220
|
+
if (idempotent) headers2["Idempotency-Key"] = uuid();
|
|
1185
2221
|
let body;
|
|
1186
|
-
if (opts.
|
|
1187
|
-
|
|
2222
|
+
if (opts.streamBody !== void 0) {
|
|
2223
|
+
headers2["Content-Type"] = "application/octet-stream";
|
|
2224
|
+
body = opts.streamBody;
|
|
2225
|
+
} else if (opts.rawBody !== void 0) {
|
|
2226
|
+
headers2["Content-Type"] = "application/octet-stream";
|
|
1188
2227
|
body = opts.rawBody;
|
|
1189
2228
|
} else if (opts.body !== void 0) {
|
|
1190
|
-
|
|
2229
|
+
headers2["Content-Type"] = "application/json";
|
|
1191
2230
|
body = JSON.stringify(opts.body);
|
|
1192
2231
|
}
|
|
1193
2232
|
const where = this.#redact(`${method} ${path}`);
|
|
1194
2233
|
let url = this.apiUrl + path;
|
|
1195
2234
|
if (opts.query) {
|
|
1196
|
-
const
|
|
2235
|
+
const q2 = new URLSearchParams();
|
|
1197
2236
|
for (const [k, v] of Object.entries(opts.query)) {
|
|
1198
|
-
if (Array.isArray(v)) for (const item of v)
|
|
1199
|
-
else if (v !== void 0)
|
|
2237
|
+
if (Array.isArray(v)) for (const item of v) q2.append(k, item);
|
|
2238
|
+
else if (v !== void 0) q2.set(k, String(v));
|
|
1200
2239
|
}
|
|
1201
|
-
const s =
|
|
2240
|
+
const s = q2.toString();
|
|
1202
2241
|
if (s) url += `?${s}`;
|
|
1203
2242
|
}
|
|
1204
2243
|
for (let attempt = 0; ; attempt++) {
|
|
@@ -1215,7 +2254,12 @@ var HttpClient = class {
|
|
|
1215
2254
|
else opts.signal?.addEventListener("abort", onAbort, { once: true });
|
|
1216
2255
|
let res;
|
|
1217
2256
|
try {
|
|
1218
|
-
|
|
2257
|
+
const init = { method, headers: headers2, body, signal: ctrl.signal };
|
|
2258
|
+
if (opts.streamBody !== void 0) {
|
|
2259
|
+
init.duplex = "half";
|
|
2260
|
+
init.redirect = "error";
|
|
2261
|
+
}
|
|
2262
|
+
res = await this.fetchImpl(url, init);
|
|
1219
2263
|
} catch (err) {
|
|
1220
2264
|
clearTimeout(timer);
|
|
1221
2265
|
opts.signal?.removeEventListener("abort", onAbort);
|
|
@@ -1411,7 +2455,7 @@ function toSeconds(ms, field) {
|
|
|
1411
2455
|
return s;
|
|
1412
2456
|
}
|
|
1413
2457
|
var METADATA_KEY = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
1414
|
-
var
|
|
2458
|
+
var enc3 = encodeURIComponent;
|
|
1415
2459
|
var Sandbox = class _Sandbox {
|
|
1416
2460
|
constructor(http, machine, opts = {}) {
|
|
1417
2461
|
this.http = http;
|
|
@@ -1419,6 +2463,7 @@ var Sandbox = class _Sandbox {
|
|
|
1419
2463
|
this.machine = machine;
|
|
1420
2464
|
this.commands = new Commands(http, machine.id, { ...opts.envs });
|
|
1421
2465
|
this.files = new Files(this.commands, http, machine.id);
|
|
2466
|
+
this.commands.stageStdin = (bytes, signal) => this.files.stageStdin(bytes, signal);
|
|
1422
2467
|
this.desktop = new Desktop(http, machine.id, this.commands, this.files);
|
|
1423
2468
|
}
|
|
1424
2469
|
http;
|
|
@@ -1509,12 +2554,12 @@ var Sandbox = class _Sandbox {
|
|
|
1509
2554
|
}
|
|
1510
2555
|
/** Fetches a snapshot by ID. Requires images:read. */
|
|
1511
2556
|
static async getSnapshot(snapshotId, opts = {}) {
|
|
1512
|
-
return new HttpClient(opts).request("GET", `/v1/snapshots/${
|
|
2557
|
+
return new HttpClient(opts).request("GET", `/v1/snapshots/${enc3(snapshotId)}`);
|
|
1513
2558
|
}
|
|
1514
2559
|
/** Deletes a snapshot. Returns false if absent. Requires images:delete. */
|
|
1515
2560
|
static async deleteSnapshot(snapshotId, opts = {}) {
|
|
1516
2561
|
try {
|
|
1517
|
-
await new HttpClient(opts).request("DELETE", `/v1/snapshots/${
|
|
2562
|
+
await new HttpClient(opts).request("DELETE", `/v1/snapshots/${enc3(snapshotId)}`);
|
|
1518
2563
|
return true;
|
|
1519
2564
|
} catch (err) {
|
|
1520
2565
|
if (err instanceof InstaboxError && err.status === 404 && err.code === "not_found") return false;
|
|
@@ -1529,7 +2574,7 @@ var Sandbox = class _Sandbox {
|
|
|
1529
2574
|
async createSnapshot(opts) {
|
|
1530
2575
|
await this.settle();
|
|
1531
2576
|
await this.untilSynced();
|
|
1532
|
-
return this.http.request("POST", `/v1/machines/${
|
|
2577
|
+
return this.http.request("POST", `/v1/machines/${enc3(this.sandboxId)}/snapshots`, { body: opts });
|
|
1533
2578
|
}
|
|
1534
2579
|
/** This sandbox's recent CPU and memory samples; see `Sandbox.getMetrics`. */
|
|
1535
2580
|
async getMetrics(opts = {}) {
|
|
@@ -1549,7 +2594,7 @@ var Sandbox = class _Sandbox {
|
|
|
1549
2594
|
* pause off. The setting stays across pause and resume.
|
|
1550
2595
|
*/
|
|
1551
2596
|
async setAutoSuspend(idleMs) {
|
|
1552
|
-
this.machine = await this.http.request("PATCH", `/v1/machines/${
|
|
2597
|
+
this.machine = await this.http.request("PATCH", `/v1/machines/${enc3(this.sandboxId)}`, {
|
|
1553
2598
|
body: { autoSuspendAfterSeconds: toIdleSeconds(idleMs) }
|
|
1554
2599
|
});
|
|
1555
2600
|
}
|
|
@@ -1563,7 +2608,7 @@ var Sandbox = class _Sandbox {
|
|
|
1563
2608
|
}
|
|
1564
2609
|
/** Replaces the sandbox's metadata (`{}` clears it). */
|
|
1565
2610
|
async setMetadata(metadata) {
|
|
1566
|
-
this.machine = await this.http.request("PATCH", `/v1/machines/${
|
|
2611
|
+
this.machine = await this.http.request("PATCH", `/v1/machines/${enc3(this.sandboxId)}`, {
|
|
1567
2612
|
body: { metadata }
|
|
1568
2613
|
});
|
|
1569
2614
|
}
|
|
@@ -1573,21 +2618,21 @@ var Sandbox = class _Sandbox {
|
|
|
1573
2618
|
* Throws `not_found` on a server without the Vault.
|
|
1574
2619
|
*/
|
|
1575
2620
|
async vault() {
|
|
1576
|
-
return this.http.request("GET", `/v1/machines/${
|
|
2621
|
+
return this.http.request("GET", `/v1/machines/${enc3(this.sandboxId)}/vault`);
|
|
1577
2622
|
}
|
|
1578
2623
|
/**
|
|
1579
2624
|
* Writes the account's current Vault items into the running sandbox now, the same write as after a boot,
|
|
1580
2625
|
* and returns its record (`error` set when the guest refused it). Requires machines:write.
|
|
1581
2626
|
*/
|
|
1582
2627
|
async pushVault() {
|
|
1583
|
-
return this.http.request("POST", `/v1/machines/${
|
|
2628
|
+
return this.http.request("POST", `/v1/machines/${enc3(this.sandboxId)}/vault`);
|
|
1584
2629
|
}
|
|
1585
2630
|
/**
|
|
1586
2631
|
* Turns the Vault off for this sandbox, for good, in any state: its next boot, resume or push removes
|
|
1587
2632
|
* what the Vault wrote and nothing is written again. Requires machines:write.
|
|
1588
2633
|
*/
|
|
1589
2634
|
async disableVault() {
|
|
1590
|
-
this.machine = await this.http.request("PATCH", `/v1/machines/${
|
|
2635
|
+
this.machine = await this.http.request("PATCH", `/v1/machines/${enc3(this.sandboxId)}`, {
|
|
1591
2636
|
body: { vault: false }
|
|
1592
2637
|
});
|
|
1593
2638
|
}
|
|
@@ -1634,7 +2679,7 @@ var Sandbox = class _Sandbox {
|
|
|
1634
2679
|
}
|
|
1635
2680
|
body.ttlSeconds = opts.ttlSeconds;
|
|
1636
2681
|
}
|
|
1637
|
-
const c = await this.http.request("POST", `/v1/machines/${
|
|
2682
|
+
const c = await this.http.request("POST", `/v1/machines/${enc3(this.sandboxId)}/connections`, { body });
|
|
1638
2683
|
return {
|
|
1639
2684
|
host: c.host,
|
|
1640
2685
|
port: c.port,
|
|
@@ -1653,7 +2698,7 @@ var Sandbox = class _Sandbox {
|
|
|
1653
2698
|
async settle(refresh = true) {
|
|
1654
2699
|
if (refresh) this.machine = await getMachine(this.http, this.sandboxId);
|
|
1655
2700
|
if (this.machine.operationId) {
|
|
1656
|
-
const op = await this.http.request("GET", `/v1/operations/${
|
|
2701
|
+
const op = await this.http.request("GET", `/v1/operations/${enc3(this.machine.operationId)}`);
|
|
1657
2702
|
await this.http.waitForOperation(op).catch(() => {
|
|
1658
2703
|
});
|
|
1659
2704
|
this.machine = await getMachine(this.http, this.sandboxId);
|
|
@@ -1681,29 +2726,29 @@ var Sandbox = class _Sandbox {
|
|
|
1681
2726
|
}
|
|
1682
2727
|
}
|
|
1683
2728
|
async mutate(method, action) {
|
|
1684
|
-
const op = await this.http.request(method, `/v1/machines/${
|
|
2729
|
+
const op = await this.http.request(method, `/v1/machines/${enc3(this.sandboxId)}/${action}`);
|
|
1685
2730
|
await this.http.waitForOperation(op);
|
|
1686
2731
|
this.machine = await getMachine(this.http, this.sandboxId);
|
|
1687
2732
|
}
|
|
1688
2733
|
};
|
|
1689
2734
|
async function getMachine(http, id) {
|
|
1690
|
-
return http.request("GET", `/v1/machines/${
|
|
2735
|
+
return http.request("GET", `/v1/machines/${enc3(id)}`);
|
|
1691
2736
|
}
|
|
1692
2737
|
async function getMetrics(http, id, opts) {
|
|
1693
|
-
const out = await http.request("GET", `/v1/machines/${
|
|
2738
|
+
const out = await http.request("GET", `/v1/machines/${enc3(id)}/metrics`, {
|
|
1694
2739
|
query: { since: opts.since?.toISOString() }
|
|
1695
2740
|
});
|
|
1696
2741
|
return out.metrics.map((s) => ({ ...s, timestamp: new Date(s.timestamp) }));
|
|
1697
2742
|
}
|
|
1698
2743
|
async function getUsage(http, id, opts) {
|
|
1699
|
-
const u = await http.request("GET", `/v1/machines/${
|
|
2744
|
+
const u = await http.request("GET", `/v1/machines/${enc3(id)}/usage`, {
|
|
1700
2745
|
query: { from: opts.from?.toISOString(), to: opts.to?.toISOString() }
|
|
1701
2746
|
});
|
|
1702
2747
|
return { ...u, from: new Date(u.from), to: new Date(u.to) };
|
|
1703
2748
|
}
|
|
1704
2749
|
async function killMachine(http, id) {
|
|
1705
2750
|
try {
|
|
1706
|
-
const op = await http.request("DELETE", `/v1/machines/${
|
|
2751
|
+
const op = await http.request("DELETE", `/v1/machines/${enc3(id)}`, {
|
|
1707
2752
|
headers: { "X-Confirm-Delete": id }
|
|
1708
2753
|
});
|
|
1709
2754
|
await http.waitForOperation(op);
|
|
@@ -1766,6 +2811,7 @@ export {
|
|
|
1766
2811
|
LIMIT_CODES,
|
|
1767
2812
|
MAX_FILE_BYTES,
|
|
1768
2813
|
MAX_STDIN_BYTES,
|
|
2814
|
+
MAX_UPLOAD_BYTES,
|
|
1769
2815
|
Sandbox,
|
|
1770
2816
|
isLimitCode
|
|
1771
2817
|
};
|