@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.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) 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,534 @@ 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
|
+
var RESERVED = /* @__PURE__ */ new Set([
|
|
1279
|
+
"CON",
|
|
1280
|
+
"PRN",
|
|
1281
|
+
"AUX",
|
|
1282
|
+
"NUL",
|
|
1283
|
+
"CONIN$",
|
|
1284
|
+
"CONOUT$",
|
|
1285
|
+
...["COM", "LPT"].flatMap((d) => [1, 2, 3, 4, 5, 6, 7, 8, 9, "\xB9", "\xB2", "\xB3"].map((i) => `${d}${i}`))
|
|
1286
|
+
]);
|
|
1287
|
+
var WINDOWS = globalThis.process?.platform === "win32";
|
|
1288
|
+
function components(name, windows = WINDOWS) {
|
|
1289
|
+
if (name.startsWith("/")) throw unsafe(name);
|
|
1290
|
+
const parts = [];
|
|
1291
|
+
for (const p of name.split("/")) {
|
|
1292
|
+
if (p === "" || p === ".") continue;
|
|
1293
|
+
if (p === ".." || p.includes("\\") || p.includes("\0")) throw unsafe(name);
|
|
1294
|
+
if (windows && (p.includes(":") || p.endsWith(".") || p.endsWith(" ") || RESERVED.has(p.split(".")[0].replace(/ +$/, "").toUpperCase()))) {
|
|
1295
|
+
throw unsafe(name);
|
|
1296
|
+
}
|
|
1297
|
+
parts.push(p);
|
|
1298
|
+
}
|
|
1299
|
+
return parts;
|
|
1300
|
+
}
|
|
1301
|
+
async function unpackLocal(n, src, dest, windows = WINDOWS) {
|
|
1302
|
+
await n.fsp.mkdir(dest, { recursive: true });
|
|
1303
|
+
const root = await n.fsp.realpath(dest);
|
|
1304
|
+
const gunzip = n.zlib.createGunzip();
|
|
1305
|
+
n.stream.pipeline(n.stream.Readable.from(src, { objectMode: false }), gunzip, () => {
|
|
1306
|
+
});
|
|
1307
|
+
const dirModes = /* @__PURE__ */ new Map();
|
|
1308
|
+
let files = 0;
|
|
1309
|
+
const writable = async (abs, st) => {
|
|
1310
|
+
const mode = st.mode & 4095;
|
|
1311
|
+
if ((mode & 192) === 192 || dirModes.has(abs)) return;
|
|
1312
|
+
dirModes.set(abs, mode);
|
|
1313
|
+
await n.fsp.chmod(abs, mode | 192);
|
|
1314
|
+
};
|
|
1315
|
+
await writable(root, await n.fsp.stat(root));
|
|
1316
|
+
const ensureDir = async (parts, name) => {
|
|
1317
|
+
let cur = root;
|
|
1318
|
+
for (const p of parts) {
|
|
1319
|
+
cur = n.path.join(cur, p);
|
|
1320
|
+
let st;
|
|
1321
|
+
try {
|
|
1322
|
+
st = await n.fsp.lstat(cur);
|
|
1323
|
+
} catch (err) {
|
|
1324
|
+
if (err.code !== "ENOENT") throw err;
|
|
1325
|
+
}
|
|
1326
|
+
if (!st) await n.fsp.mkdir(cur, { mode: 493 });
|
|
1327
|
+
else if (!st.isDirectory()) throw unsafe(name);
|
|
1328
|
+
else await writable(cur, st);
|
|
1329
|
+
}
|
|
1330
|
+
return cur;
|
|
1331
|
+
};
|
|
1332
|
+
const clear = async (abs, name) => {
|
|
1333
|
+
let st;
|
|
1334
|
+
try {
|
|
1335
|
+
st = await n.fsp.lstat(abs);
|
|
1336
|
+
} catch {
|
|
1337
|
+
return;
|
|
1338
|
+
}
|
|
1339
|
+
if (st.isDirectory()) {
|
|
1340
|
+
throw new InstaboxError(`${name} is a directory locally; the archive has a file there`, {
|
|
1341
|
+
code: "local_io_error"
|
|
1342
|
+
});
|
|
1343
|
+
}
|
|
1344
|
+
await n.fsp.unlink(abs);
|
|
1345
|
+
};
|
|
1346
|
+
let ok = false;
|
|
1347
|
+
try {
|
|
1348
|
+
for await (const e of untarStream(gunzip)) {
|
|
1349
|
+
const parts = components(e.name, windows);
|
|
1350
|
+
if (parts.length === 0) {
|
|
1351
|
+
for await (const _ of e.data) void _;
|
|
1352
|
+
continue;
|
|
1353
|
+
}
|
|
1354
|
+
const parent = await ensureDir(parts.slice(0, -1), e.name);
|
|
1355
|
+
const abs = n.path.join(parent, parts[parts.length - 1]);
|
|
1356
|
+
if (e.type === "dir") {
|
|
1357
|
+
await ensureDir(parts, e.name);
|
|
1358
|
+
dirModes.set(abs, e.mode);
|
|
1359
|
+
} else if (e.type === "file") {
|
|
1360
|
+
await clear(abs, e.name);
|
|
1361
|
+
await n.sp.pipeline(
|
|
1362
|
+
n.stream.Readable.from(e.data, { objectMode: false }),
|
|
1363
|
+
n.fs.createWriteStream(abs, { flags: "wx", mode: e.mode | 128 })
|
|
1364
|
+
);
|
|
1365
|
+
await n.fsp.chmod(abs, e.mode);
|
|
1366
|
+
files++;
|
|
1367
|
+
} else if (e.type === "symlink") {
|
|
1368
|
+
await clear(abs, e.name);
|
|
1369
|
+
await n.fsp.symlink(e.linkname, abs);
|
|
1370
|
+
} else if (e.type === "link") {
|
|
1371
|
+
const tparts = components(e.linkname, windows);
|
|
1372
|
+
const target = n.path.join(await ensureDir(tparts.slice(0, -1), e.linkname), tparts[tparts.length - 1] ?? "");
|
|
1373
|
+
const st = await n.fsp.lstat(target).catch(() => void 0);
|
|
1374
|
+
if (!st?.isFile()) throw unsafe(e.linkname);
|
|
1375
|
+
await clear(abs, e.name);
|
|
1376
|
+
await n.fsp.copyFile(target, abs);
|
|
1377
|
+
files++;
|
|
1378
|
+
}
|
|
1379
|
+
}
|
|
1380
|
+
ok = true;
|
|
1381
|
+
} finally {
|
|
1382
|
+
const depth = (p) => p.split(n.path.sep).length;
|
|
1383
|
+
for (const [abs, mode] of [...dirModes].sort((a, b) => depth(b[0]) - depth(a[0]))) {
|
|
1384
|
+
await n.fsp.chmod(abs, mode).catch((err) => {
|
|
1385
|
+
if (ok) throw err;
|
|
1386
|
+
});
|
|
1387
|
+
}
|
|
1388
|
+
}
|
|
1389
|
+
return files;
|
|
1390
|
+
}
|
|
1391
|
+
|
|
833
1392
|
// src/files.ts
|
|
834
1393
|
var MAX_FILE_BYTES = 10 * 1024 * 1024;
|
|
1394
|
+
var MAX_UPLOAD_BYTES = 5 * 1024 * 1024 * 1024;
|
|
835
1395
|
var TRANSFER_TIMEOUT_MS = 3e5;
|
|
1396
|
+
var TRANSFER_MAX_MS = 72e5 + 12e4;
|
|
1397
|
+
var TRANSFER_IDLE_MS = 12e4;
|
|
1398
|
+
var TRANSFER_EXEC_MS = 6e5;
|
|
836
1399
|
var WRITE_CHUNK_B64 = 48 * 1024;
|
|
837
1400
|
var READ_CHUNK_BYTES = 512 * 1024;
|
|
1401
|
+
var PROBE_PATH = "instabox-sdk-route-probe";
|
|
838
1402
|
var Files = class {
|
|
839
1403
|
/** @internal */
|
|
840
1404
|
constructor(commands, http, sandboxId) {
|
|
@@ -848,22 +1412,45 @@ var Files = class {
|
|
|
848
1412
|
home;
|
|
849
1413
|
/** False once a server answered that it has no file routes. */
|
|
850
1414
|
routes = true;
|
|
1415
|
+
/** True once a server answered on a file route, so a stream need not probe for it. */
|
|
1416
|
+
routesSeen = false;
|
|
1417
|
+
get filesPath() {
|
|
1418
|
+
return `/v1/machines/${encodeURIComponent(this.sandboxId ?? "")}/files`;
|
|
1419
|
+
}
|
|
851
1420
|
async read(path, opts = {}) {
|
|
852
1421
|
const limit = opts.maxBytes ?? MAX_FILE_BYTES;
|
|
853
|
-
|
|
854
|
-
const
|
|
1422
|
+
if (!(limit >= 0)) throw new InstaboxError("maxBytes must be a number, at least 0", { code: "bad_request" });
|
|
1423
|
+
const res = await this.openRoute(path);
|
|
1424
|
+
const bytes = res ? await this.readRoute(res, path, limit) : await this.readExec(path, limit);
|
|
855
1425
|
return opts.format === "bytes" ? bytes : decodeUtf8(bytes);
|
|
856
1426
|
}
|
|
857
|
-
/**
|
|
858
|
-
|
|
1427
|
+
/**
|
|
1428
|
+
* Opens a file for reading as a stream, with no size cap: the bytes arrive as the server sends them,
|
|
1429
|
+
* so a file of any size reads in bounded memory. Errors before the first byte (`not_found`, a
|
|
1430
|
+
* directory) reject the promise; a stream cut short errors with `file_changed`. Read it with
|
|
1431
|
+
* `for await`, `getReader()`, or in Node `Readable.fromWeb(stream)` and `pipeline`. On a server
|
|
1432
|
+
* without the file routes the file is read over exec first (at most 10 MiB).
|
|
1433
|
+
*/
|
|
1434
|
+
async readStream(path, opts = {}) {
|
|
1435
|
+
const res = await this.openRoute(path, opts.signal);
|
|
1436
|
+
if (!res) return iterable(oneChunk(await this.readExec(path, MAX_FILE_BYTES)));
|
|
1437
|
+
return iterable(this.countedBody(res, path, opts.signal));
|
|
1438
|
+
}
|
|
1439
|
+
/**
|
|
1440
|
+
* `GET .../files/content` of `path` (or of `abs`, already absolute); undefined when the server has
|
|
1441
|
+
* no such route. `not_found` and `not_a_file` become `not_found`: a directory is not a file either.
|
|
1442
|
+
*/
|
|
1443
|
+
async openRoute(path, signal, abs) {
|
|
859
1444
|
if (!this.http || !this.sandboxId || !this.routes) return void 0;
|
|
860
|
-
|
|
861
|
-
let res;
|
|
1445
|
+
abs ??= await this.absolute(path);
|
|
862
1446
|
try {
|
|
863
|
-
res = await this.http.send("GET",
|
|
1447
|
+
const res = await this.http.send("GET", `${this.filesPath}/content`, {
|
|
864
1448
|
query: { path: abs },
|
|
865
|
-
timeoutMs: TRANSFER_TIMEOUT_MS
|
|
1449
|
+
timeoutMs: TRANSFER_TIMEOUT_MS,
|
|
1450
|
+
signal
|
|
866
1451
|
});
|
|
1452
|
+
this.routesSeen = true;
|
|
1453
|
+
return res;
|
|
867
1454
|
} catch (err) {
|
|
868
1455
|
if (routeMissing(err)) {
|
|
869
1456
|
this.routes = false;
|
|
@@ -879,19 +1466,72 @@ var Files = class {
|
|
|
879
1466
|
}
|
|
880
1467
|
throw err;
|
|
881
1468
|
}
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
1469
|
+
}
|
|
1470
|
+
/** Reads a whole response body of `path`, at most `limit` bytes. */
|
|
1471
|
+
async readRoute(res, path, limit) {
|
|
1472
|
+
try {
|
|
1473
|
+
const declared = Number(res.headers.get("Content-Length") ?? NaN);
|
|
1474
|
+
if (Number.isSafeInteger(declared) && declared > limit) {
|
|
1475
|
+
void res.body?.cancel().catch(() => {
|
|
1476
|
+
});
|
|
1477
|
+
throw new InstaboxError(`${path} is larger than the ${limit}-byte limit of files.read`, {
|
|
1478
|
+
code: "file_too_large"
|
|
1479
|
+
});
|
|
1480
|
+
}
|
|
1481
|
+
const bytes = await readBody(res, limit, path);
|
|
1482
|
+
if (Number.isSafeInteger(declared) && bytes.length !== declared) {
|
|
1483
|
+
throw new InstaboxError(`got ${bytes.length} of ${declared} bytes of ${path}`, { code: "file_changed" });
|
|
1484
|
+
}
|
|
1485
|
+
return bytes;
|
|
1486
|
+
} finally {
|
|
1487
|
+
this.http?.release(res);
|
|
893
1488
|
}
|
|
894
|
-
|
|
1489
|
+
}
|
|
1490
|
+
/** A response body as a stream that errors with `file_changed` when it ends short of Content-Length. */
|
|
1491
|
+
countedBody(res, path, signal) {
|
|
1492
|
+
const http = this.http;
|
|
1493
|
+
const declared = Number(res.headers.get("Content-Length") ?? NaN);
|
|
1494
|
+
const reader = res.body?.getReader();
|
|
1495
|
+
let n = 0;
|
|
1496
|
+
return new ReadableStream(
|
|
1497
|
+
{
|
|
1498
|
+
async pull(c) {
|
|
1499
|
+
if (!reader) {
|
|
1500
|
+
http.release(res);
|
|
1501
|
+
return c.close();
|
|
1502
|
+
}
|
|
1503
|
+
let r;
|
|
1504
|
+
try {
|
|
1505
|
+
r = await reader.read();
|
|
1506
|
+
} catch (err) {
|
|
1507
|
+
http.release(res);
|
|
1508
|
+
if (signal?.aborted) return c.error(new InstaboxError(`reading ${path} was aborted`, { code: "aborted" }));
|
|
1509
|
+
const msg = err?.message ?? String(err);
|
|
1510
|
+
return c.error(
|
|
1511
|
+
new InstaboxError(`reading ${path} stopped after ${n} bytes: ${msg}`, {
|
|
1512
|
+
code: "file_changed",
|
|
1513
|
+
retryable: true,
|
|
1514
|
+
cause: err
|
|
1515
|
+
})
|
|
1516
|
+
);
|
|
1517
|
+
}
|
|
1518
|
+
if (r.done) {
|
|
1519
|
+
http.release(res);
|
|
1520
|
+
if (Number.isSafeInteger(declared) && n !== declared) {
|
|
1521
|
+
return c.error(new InstaboxError(`got ${n} of ${declared} bytes of ${path}`, { code: "file_changed" }));
|
|
1522
|
+
}
|
|
1523
|
+
return c.close();
|
|
1524
|
+
}
|
|
1525
|
+
n += r.value.length;
|
|
1526
|
+
c.enqueue(r.value);
|
|
1527
|
+
},
|
|
1528
|
+
cancel(reason) {
|
|
1529
|
+
http.release(res);
|
|
1530
|
+
return reader?.cancel(reason);
|
|
1531
|
+
}
|
|
1532
|
+
},
|
|
1533
|
+
{ highWaterMark: 0 }
|
|
1534
|
+
);
|
|
895
1535
|
}
|
|
896
1536
|
async readExec(path, limit) {
|
|
897
1537
|
const p = arg(path);
|
|
@@ -924,57 +1564,201 @@ var Files = class {
|
|
|
924
1564
|
return bytes;
|
|
925
1565
|
}
|
|
926
1566
|
/**
|
|
927
|
-
* Writes a file, creating parent directories. Replaces the file atomically (temp file + rename)
|
|
928
|
-
* Throws `is_a_directory` when `path` is a directory.
|
|
1567
|
+
* Writes a file, creating parent directories. Replaces the file atomically (temp file + rename), so
|
|
1568
|
+
* a failed or aborted write leaves the old file. Throws `is_a_directory` when `path` is a directory.
|
|
1569
|
+
*
|
|
1570
|
+
* `data` is a string, bytes, or a stream (a Node `Readable`, a web `ReadableStream`, an
|
|
1571
|
+
* `AsyncIterable` of chunks): a stream is sent as it is read, in bounded memory, up to the server's
|
|
1572
|
+
* 5 GiB. The size and SHA-256 the server reports are checked against what was sent
|
|
1573
|
+
* (`transfer_mismatch` when they differ). On a server without the file routes, writes go over exec
|
|
1574
|
+
* and are capped at 10 MiB (`file_too_large`).
|
|
929
1575
|
*/
|
|
930
|
-
async write(path, data) {
|
|
931
|
-
const bytes =
|
|
932
|
-
if (bytes
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
1576
|
+
async write(path, data, opts = {}) {
|
|
1577
|
+
const bytes = asBytes(data);
|
|
1578
|
+
if (bytes) {
|
|
1579
|
+
if (await this.writeRoute(path, bytes, opts.signal)) return { path };
|
|
1580
|
+
if (bytes.length > MAX_FILE_BYTES) throw tooLargeForExec();
|
|
1581
|
+
await this.writeExec(path, bytes);
|
|
1582
|
+
return { path };
|
|
1583
|
+
}
|
|
1584
|
+
const src = asIterable(data);
|
|
1585
|
+
if (await this.routesAvailable(opts.signal)) {
|
|
1586
|
+
if (await this.writeRoute(path, src, opts.signal)) return { path };
|
|
1587
|
+
throw noRoutes();
|
|
936
1588
|
}
|
|
937
|
-
|
|
938
|
-
await this.writeExec(path, bytes);
|
|
1589
|
+
await this.writeExec(path, await collect(src, MAX_FILE_BYTES));
|
|
939
1590
|
return { path };
|
|
940
1591
|
}
|
|
941
1592
|
/**
|
|
942
1593
|
* Writes over `PUT .../files?parents=true`, which writes a temp file beside the target and renames
|
|
943
1594
|
* it into place once every byte arrived. False when the server has no such route.
|
|
944
1595
|
*/
|
|
945
|
-
async
|
|
1596
|
+
async writeRoute(path, body, signal) {
|
|
946
1597
|
if (!this.http || !this.sandboxId || !this.routes) return false;
|
|
947
1598
|
const abs = await this.absolute(path);
|
|
948
|
-
let res;
|
|
949
1599
|
try {
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
1600
|
+
return await this.put(abs, body, { parents: "true" }, signal) !== void 0;
|
|
1601
|
+
} catch (err) {
|
|
1602
|
+
if (err instanceof InstaboxError && err.code === "not_a_file") {
|
|
1603
|
+
const dir = await this.commands.exec(`test -d ${arg(path)}`).catch(() => void 0);
|
|
1604
|
+
if (dir?.exitCode === 0) {
|
|
1605
|
+
throw new InstaboxError(`is a directory: ${path}`, { status: 409, code: "is_a_directory", cause: err });
|
|
1606
|
+
}
|
|
1607
|
+
}
|
|
1608
|
+
throw err;
|
|
1609
|
+
}
|
|
1610
|
+
}
|
|
1611
|
+
/**
|
|
1612
|
+
* True when the server has the file routes. A stream can be sent only once, so before the first one
|
|
1613
|
+
* the route is probed with a relative path, which the server refuses (400) before touching the
|
|
1614
|
+
* sandbox; a server without the route answers 404 or 405.
|
|
1615
|
+
*/
|
|
1616
|
+
async routesAvailable(signal) {
|
|
1617
|
+
if (!this.http || !this.sandboxId || !this.routes) return false;
|
|
1618
|
+
if (this.routesSeen) return true;
|
|
1619
|
+
try {
|
|
1620
|
+
await this.http.request("PUT", this.filesPath, {
|
|
1621
|
+
query: { path: PROBE_PATH },
|
|
1622
|
+
rawBody: new Uint8Array(0),
|
|
953
1623
|
idempotent: false,
|
|
954
1624
|
retry: true,
|
|
955
|
-
|
|
1625
|
+
signal
|
|
956
1626
|
});
|
|
957
1627
|
} catch (err) {
|
|
958
1628
|
if (routeMissing(err)) {
|
|
959
1629
|
this.routes = false;
|
|
960
1630
|
return false;
|
|
961
1631
|
}
|
|
962
|
-
if (err instanceof InstaboxError
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
1632
|
+
if (!(err instanceof InstaboxError) || err.status !== 400) throw err;
|
|
1633
|
+
}
|
|
1634
|
+
this.routesSeen = true;
|
|
1635
|
+
return true;
|
|
1636
|
+
}
|
|
1637
|
+
/**
|
|
1638
|
+
* `PUT .../files` of `body` to the absolute path `abs`, checking the size and SHA-256 the server
|
|
1639
|
+
* reports. Bytes are retried on 502-504 (the server replaces the file atomically, so a repeat writes
|
|
1640
|
+
* the same bytes); a stream is sent once, as it is read, and given up when it moves nothing for
|
|
1641
|
+
* 2 minutes. Undefined when the server has no such route.
|
|
1642
|
+
*/
|
|
1643
|
+
async put(abs, body, query, signal) {
|
|
1644
|
+
if (!this.http || !this.sandboxId || !this.routes) return void 0;
|
|
1645
|
+
let res;
|
|
1646
|
+
let sent;
|
|
1647
|
+
let want;
|
|
1648
|
+
if (body instanceof Uint8Array) {
|
|
1649
|
+
try {
|
|
1650
|
+
res = await this.http.request("PUT", this.filesPath, {
|
|
1651
|
+
query: { path: abs, ...query },
|
|
1652
|
+
rawBody: body,
|
|
1653
|
+
idempotent: false,
|
|
1654
|
+
retry: true,
|
|
1655
|
+
timeoutMs: bufferedTimeout(body.length),
|
|
1656
|
+
signal
|
|
1657
|
+
});
|
|
1658
|
+
} catch (err) {
|
|
1659
|
+
if (routeMissing(err)) {
|
|
1660
|
+
this.routes = false;
|
|
1661
|
+
return void 0;
|
|
966
1662
|
}
|
|
1663
|
+
throw err;
|
|
967
1664
|
}
|
|
968
|
-
|
|
1665
|
+
sent = body.length;
|
|
1666
|
+
want = await sha256Hex(body);
|
|
1667
|
+
} else {
|
|
1668
|
+
const up = await this.putStream(abs, body, query, signal);
|
|
1669
|
+
if (!up) return void 0;
|
|
1670
|
+
({ res, sent, want } = up);
|
|
969
1671
|
}
|
|
970
|
-
|
|
971
|
-
if (res?.size !==
|
|
1672
|
+
this.routesSeen = true;
|
|
1673
|
+
if (res?.size !== sent || want !== void 0 && res.sha256 !== want) {
|
|
972
1674
|
throw new InstaboxError(
|
|
973
|
-
`the sandbox received ${res?.size} bytes with sha256 ${res?.sha256}; sent ${
|
|
1675
|
+
`the sandbox received ${res?.size} bytes with sha256 ${res?.sha256}; sent ${sent} with ${want}`,
|
|
974
1676
|
{ code: "transfer_mismatch" }
|
|
975
1677
|
);
|
|
976
1678
|
}
|
|
977
|
-
return
|
|
1679
|
+
return { size: sent };
|
|
1680
|
+
}
|
|
1681
|
+
async putStream(abs, src, query, signal) {
|
|
1682
|
+
const hash = await sha256Stream();
|
|
1683
|
+
const ctrl = new AbortController();
|
|
1684
|
+
let idle;
|
|
1685
|
+
let idleFired = false;
|
|
1686
|
+
const touch = () => {
|
|
1687
|
+
clearTimeout(idle);
|
|
1688
|
+
idle = setTimeout(() => {
|
|
1689
|
+
idleFired = true;
|
|
1690
|
+
ctrl.abort();
|
|
1691
|
+
}, TRANSFER_IDLE_MS);
|
|
1692
|
+
};
|
|
1693
|
+
const onAbort = () => ctrl.abort();
|
|
1694
|
+
if (signal?.aborted) ctrl.abort();
|
|
1695
|
+
else signal?.addEventListener("abort", onAbort, { once: true });
|
|
1696
|
+
const it = src[Symbol.asyncIterator]();
|
|
1697
|
+
let sent = 0;
|
|
1698
|
+
let srcErr;
|
|
1699
|
+
const stream = new ReadableStream(
|
|
1700
|
+
{
|
|
1701
|
+
async pull(c) {
|
|
1702
|
+
touch();
|
|
1703
|
+
let r;
|
|
1704
|
+
try {
|
|
1705
|
+
r = await it.next();
|
|
1706
|
+
if (!r.done) {
|
|
1707
|
+
const b = chunkBytes(r.value);
|
|
1708
|
+
sent += b.length;
|
|
1709
|
+
if (sent > MAX_UPLOAD_BYTES) {
|
|
1710
|
+
throw new InstaboxError(`data is larger than the ${MAX_UPLOAD_BYTES}-byte limit of files.write`, {
|
|
1711
|
+
status: 413,
|
|
1712
|
+
code: "too_large"
|
|
1713
|
+
});
|
|
1714
|
+
}
|
|
1715
|
+
hash?.update(b);
|
|
1716
|
+
if (b.length) c.enqueue(b);
|
|
1717
|
+
return;
|
|
1718
|
+
}
|
|
1719
|
+
} catch (err) {
|
|
1720
|
+
clearTimeout(idle);
|
|
1721
|
+
srcErr = sourceError(err);
|
|
1722
|
+
throw srcErr;
|
|
1723
|
+
}
|
|
1724
|
+
clearTimeout(idle);
|
|
1725
|
+
c.close();
|
|
1726
|
+
},
|
|
1727
|
+
async cancel() {
|
|
1728
|
+
clearTimeout(idle);
|
|
1729
|
+
await it.return?.();
|
|
1730
|
+
}
|
|
1731
|
+
},
|
|
1732
|
+
{ highWaterMark: 0 }
|
|
1733
|
+
);
|
|
1734
|
+
try {
|
|
1735
|
+
const res = await this.http.request("PUT", this.filesPath, {
|
|
1736
|
+
query: { path: abs, ...query },
|
|
1737
|
+
streamBody: stream,
|
|
1738
|
+
idempotent: false,
|
|
1739
|
+
timeoutMs: TRANSFER_MAX_MS,
|
|
1740
|
+
signal: ctrl.signal
|
|
1741
|
+
});
|
|
1742
|
+
return { res, sent, want: hash?.digest("hex") };
|
|
1743
|
+
} catch (err) {
|
|
1744
|
+
if (srcErr) throw srcErr;
|
|
1745
|
+
if (idleFired) {
|
|
1746
|
+
throw new InstaboxTimeoutError(`the upload to ${abs} moved nothing for ${TRANSFER_IDLE_MS / 1e3} s`, {
|
|
1747
|
+
code: "request_timeout",
|
|
1748
|
+
cause: err
|
|
1749
|
+
});
|
|
1750
|
+
}
|
|
1751
|
+
if (routeMissing(err)) {
|
|
1752
|
+
this.routes = false;
|
|
1753
|
+
return void 0;
|
|
1754
|
+
}
|
|
1755
|
+
throw err;
|
|
1756
|
+
} finally {
|
|
1757
|
+
clearTimeout(idle);
|
|
1758
|
+
signal?.removeEventListener("abort", onAbort);
|
|
1759
|
+
void it.return?.()?.catch?.(() => {
|
|
1760
|
+
});
|
|
1761
|
+
}
|
|
978
1762
|
}
|
|
979
1763
|
async writeExec(path, bytes) {
|
|
980
1764
|
const p = arg(path);
|
|
@@ -999,6 +1783,172 @@ var Files = class {
|
|
|
999
1783
|
throw err;
|
|
1000
1784
|
}
|
|
1001
1785
|
}
|
|
1786
|
+
/**
|
|
1787
|
+
* Puts `src` at the absolute temporary path `abs` (mode 0600): over the file route, or in base64
|
|
1788
|
+
* chunks over exec (`instabox push`'s fallback) on a server without it.
|
|
1789
|
+
*/
|
|
1790
|
+
async putTemp(abs, src, signal) {
|
|
1791
|
+
const replayable = src instanceof Uint8Array;
|
|
1792
|
+
if (replayable || await this.routesAvailable(signal)) {
|
|
1793
|
+
if (await this.put(abs, src, { mode: "0600" }, signal)) return;
|
|
1794
|
+
if (!replayable) throw noRoutes();
|
|
1795
|
+
}
|
|
1796
|
+
let first = true;
|
|
1797
|
+
for await (const chunk of rechunk(replayable ? [src] : src, EXEC_CHUNK_BYTES)) {
|
|
1798
|
+
if (signal?.aborted) throw new InstaboxError("the transfer was aborted", { code: "aborted" });
|
|
1799
|
+
await this.transferExec(PUSH_CHUNK_SCRIPT, { IB_TMP: abs, IB_FIRST: first ? "1" : "0" }, "", signal, {
|
|
1800
|
+
stdin: bytesToBase64(chunk)
|
|
1801
|
+
});
|
|
1802
|
+
first = false;
|
|
1803
|
+
}
|
|
1804
|
+
if (first) await this.transferExec(PUSH_CHUNK_SCRIPT, { IB_TMP: abs, IB_FIRST: "1" }, "", signal, { stdin: "" });
|
|
1805
|
+
}
|
|
1806
|
+
/**
|
|
1807
|
+
* Runs a transfer script and returns its stdout after `mark`. A non-zero exit throws `transfer_failed`
|
|
1808
|
+
* (`permission_denied`, status 403, when the sandbox refused access), as the CLI reports it.
|
|
1809
|
+
*/
|
|
1810
|
+
async transferExec(cmd, envs, mark, signal, extra = {}) {
|
|
1811
|
+
const r = await this.commands.exec(cmd, { envs, timeoutMs: TRANSFER_EXEC_MS, signal, stdin: extra.stdin });
|
|
1812
|
+
if (r.timedOut) {
|
|
1813
|
+
throw new InstaboxTimeoutError(`the transfer timed out after ${TRANSFER_EXEC_MS / 1e3} s in the sandbox`, {
|
|
1814
|
+
code: "request_timeout"
|
|
1815
|
+
});
|
|
1816
|
+
}
|
|
1817
|
+
if (r.exitCode !== 0) {
|
|
1818
|
+
const msg = r.stderr.trim() || `exit status ${r.exitCode}`;
|
|
1819
|
+
if (/Permission denied|Operation not permitted/.test(msg)) {
|
|
1820
|
+
throw new InstaboxError(`in the sandbox: ${msg}`, { status: 403, code: "permission_denied" });
|
|
1821
|
+
}
|
|
1822
|
+
throw new InstaboxError(`in the sandbox: ${msg}`, { code: "transfer_failed" });
|
|
1823
|
+
}
|
|
1824
|
+
if (!mark) return "";
|
|
1825
|
+
const i = r.stdout.indexOf(mark);
|
|
1826
|
+
if (i < 0 || r.truncated)
|
|
1827
|
+
throw new InstaboxError("unexpected output from the sandbox", { code: "invalid_response" });
|
|
1828
|
+
return r.stdout.slice(i + mark.length);
|
|
1829
|
+
}
|
|
1830
|
+
/**
|
|
1831
|
+
* Uploads a local directory's contents into `remoteDir` in one call, as one gzipped tar, the way
|
|
1832
|
+
* `instabox push` does: streamed over `PUT .../files` to a temporary file, then unpacked in the
|
|
1833
|
+
* sandbox with `tar`. `remoteDir` and its parents are created; existing files there are replaced,
|
|
1834
|
+
* others kept. In a git work tree only what git tracks is uploaded (pass `all: true` to add
|
|
1835
|
+
* untracked files git does not ignore, `git: false` to upload everything). Symlinks are uploaded as
|
|
1836
|
+
* symlinks, never followed; sockets, FIFOs and devices are skipped. Node.js (or Bun, Deno) only.
|
|
1837
|
+
*/
|
|
1838
|
+
async upload(localDir, remoteDir, opts = {}) {
|
|
1839
|
+
const n = await node();
|
|
1840
|
+
const st = await n.fsp.stat(localDir).catch((err) => {
|
|
1841
|
+
throw localError(err, localDir);
|
|
1842
|
+
});
|
|
1843
|
+
if (!st.isDirectory()) {
|
|
1844
|
+
throw new InstaboxError(`${localDir} is not a directory; write a single file with files.write`, {
|
|
1845
|
+
code: "not_a_directory"
|
|
1846
|
+
});
|
|
1847
|
+
}
|
|
1848
|
+
const { names } = await listLocal(n, localDir, opts).catch((err) => {
|
|
1849
|
+
throw localError(err, localDir);
|
|
1850
|
+
});
|
|
1851
|
+
const counts = { files: 0 };
|
|
1852
|
+
let bytes = 0;
|
|
1853
|
+
const packed = packLocal(n, localDir, names, counts);
|
|
1854
|
+
async function* counted() {
|
|
1855
|
+
try {
|
|
1856
|
+
for await (const chunk of packed) {
|
|
1857
|
+
bytes += chunk.length;
|
|
1858
|
+
yield chunk;
|
|
1859
|
+
}
|
|
1860
|
+
} catch (err) {
|
|
1861
|
+
throw localError(err, localDir);
|
|
1862
|
+
}
|
|
1863
|
+
}
|
|
1864
|
+
const tmp = TRANSFER_TMP_PREFIX + randomHex();
|
|
1865
|
+
try {
|
|
1866
|
+
await this.putTemp(tmp, counted(), opts.signal);
|
|
1867
|
+
const out = await this.transferExec(
|
|
1868
|
+
PUSH_FINISH_SCRIPT,
|
|
1869
|
+
{ IB_TMP: tmp, IB_DEST: remoteDir },
|
|
1870
|
+
PUSH_MARK,
|
|
1871
|
+
opts.signal
|
|
1872
|
+
);
|
|
1873
|
+
const f = out.split("\0");
|
|
1874
|
+
if (f[0] !== "ok" || !f[1])
|
|
1875
|
+
throw new InstaboxError("unexpected output from the sandbox", { code: "invalid_response" });
|
|
1876
|
+
return { path: f[1], files: counts.files, bytes };
|
|
1877
|
+
} catch (err) {
|
|
1878
|
+
await this.commands.exec(`rm -f -- ${shellQuote(tmp)}`).catch(() => {
|
|
1879
|
+
});
|
|
1880
|
+
throw err;
|
|
1881
|
+
}
|
|
1882
|
+
}
|
|
1883
|
+
/**
|
|
1884
|
+
* Downloads a sandbox directory into `localDir` in one call, as one gzipped tar, the way
|
|
1885
|
+
* `instabox pull` packs it: `tar` in the sandbox (as root when sudo allows, as the file routes read),
|
|
1886
|
+
* streamed back over `GET .../files/content` and unpacked as it arrives. `localDir` and its parents
|
|
1887
|
+
* are created; existing files are replaced, others kept. Everything under `remoteDir` comes, dot
|
|
1888
|
+
* files and empty directories included; symlinks arrive as symlinks. No entry can write outside
|
|
1889
|
+
* `localDir`. Node.js (or Bun, Deno) only.
|
|
1890
|
+
*/
|
|
1891
|
+
async download(remoteDir, localDir, opts = {}) {
|
|
1892
|
+
const n = await node();
|
|
1893
|
+
const tmp = TRANSFER_TMP_PREFIX + randomHex();
|
|
1894
|
+
const envs = { IB_PATH: remoteDir };
|
|
1895
|
+
const f = (await this.transferExec(pullStartCmd(tmp), envs, PULL_MARK, opts.signal)).split("\0");
|
|
1896
|
+
if (f[0] === "missing") {
|
|
1897
|
+
throw new InstaboxError(`directory not found: ${remoteDir}`, { status: 404, code: "not_found" });
|
|
1898
|
+
}
|
|
1899
|
+
if (f[0] === "not_a_dir") {
|
|
1900
|
+
throw new InstaboxError(`${f[1]} is not a directory; read a single file with files.read or files.readStream`, {
|
|
1901
|
+
code: "not_a_directory"
|
|
1902
|
+
});
|
|
1903
|
+
}
|
|
1904
|
+
const size = Number(f[2]);
|
|
1905
|
+
if (f[0] !== "dir" || !f[1] || !Number.isSafeInteger(size) || size < 0) {
|
|
1906
|
+
throw new InstaboxError("unexpected output from the sandbox", { code: "invalid_response" });
|
|
1907
|
+
}
|
|
1908
|
+
try {
|
|
1909
|
+
let bytes = 0;
|
|
1910
|
+
const src = this.fetchTemp(tmp, size, envs, opts.signal);
|
|
1911
|
+
async function* counted() {
|
|
1912
|
+
for await (const chunk of src) {
|
|
1913
|
+
bytes += chunk.length;
|
|
1914
|
+
yield chunk;
|
|
1915
|
+
}
|
|
1916
|
+
}
|
|
1917
|
+
const files = await unpackLocal(n, counted(), localDir).catch((err) => {
|
|
1918
|
+
throw localError(err, localDir);
|
|
1919
|
+
});
|
|
1920
|
+
if (bytes !== size) {
|
|
1921
|
+
throw new InstaboxError(`got ${bytes} of ${size} bytes of the archive`, { code: "file_changed" });
|
|
1922
|
+
}
|
|
1923
|
+
return { path: localDir, remotePath: f[1], files, bytes };
|
|
1924
|
+
} finally {
|
|
1925
|
+
await this.commands.exec(pullRemoveCmd(tmp), { envs }).catch(() => {
|
|
1926
|
+
});
|
|
1927
|
+
}
|
|
1928
|
+
}
|
|
1929
|
+
/** The temporary archive's bytes: over the file route, or in base64 chunks over exec without it. */
|
|
1930
|
+
async *fetchTemp(tmp, size, envs, signal) {
|
|
1931
|
+
const res = await this.openRoute(tmp, signal, tmp);
|
|
1932
|
+
if (res) {
|
|
1933
|
+
yield* iterable(this.countedBody(res, tmp, signal));
|
|
1934
|
+
return;
|
|
1935
|
+
}
|
|
1936
|
+
for (let off = 0; off < size; off += EXEC_CHUNK_BYTES) {
|
|
1937
|
+
const want = Math.min(EXEC_CHUNK_BYTES, size - off);
|
|
1938
|
+
const b = base64ToBytes(await this.transferExec(pullChunkCmd(tmp, off, want), envs, PULL_MARK, signal));
|
|
1939
|
+
if (b.length !== want) throw new InstaboxError("the archive changed while reading it", { code: "file_changed" });
|
|
1940
|
+
yield b;
|
|
1941
|
+
}
|
|
1942
|
+
}
|
|
1943
|
+
/**
|
|
1944
|
+
* @internal Stages bytes as a temporary file for a command's stdin (`instabox exec --stdin`'s way) and
|
|
1945
|
+
* returns its path. The command removes it as it starts.
|
|
1946
|
+
*/
|
|
1947
|
+
async stageStdin(bytes, signal) {
|
|
1948
|
+
const p = STDIN_TMP_PREFIX + randomHex();
|
|
1949
|
+
await this.putTemp(p, bytes, signal);
|
|
1950
|
+
return p;
|
|
1951
|
+
}
|
|
1002
1952
|
/** The file routes take absolute paths; a relative one is relative to exec's working directory (HOME). */
|
|
1003
1953
|
async absolute(path) {
|
|
1004
1954
|
if (path.startsWith("/")) return path;
|
|
@@ -1044,6 +1994,121 @@ var Files = class {
|
|
|
1044
1994
|
function arg(path) {
|
|
1045
1995
|
return shellQuote(path.startsWith("-") ? `./${path}` : path);
|
|
1046
1996
|
}
|
|
1997
|
+
function tooLargeForExec() {
|
|
1998
|
+
return new InstaboxError(
|
|
1999
|
+
`data is larger than the ${MAX_FILE_BYTES}-byte limit of files.write on a server without the file routes`,
|
|
2000
|
+
{ code: "file_too_large" }
|
|
2001
|
+
);
|
|
2002
|
+
}
|
|
2003
|
+
function noRoutes() {
|
|
2004
|
+
return new InstaboxError("this server has no file routes (PUT /v1/machines/{id}/files) to stream to", {
|
|
2005
|
+
status: 404,
|
|
2006
|
+
code: "unsupported"
|
|
2007
|
+
});
|
|
2008
|
+
}
|
|
2009
|
+
function bufferedTimeout(size) {
|
|
2010
|
+
return Math.min(TRANSFER_MAX_MS, Math.max(TRANSFER_TIMEOUT_MS, Math.ceil(size / 65536) * 1e3));
|
|
2011
|
+
}
|
|
2012
|
+
function asBytes(data) {
|
|
2013
|
+
if (typeof data === "string") return new TextEncoder().encode(data);
|
|
2014
|
+
if (data instanceof Uint8Array) return data;
|
|
2015
|
+
if (data instanceof ArrayBuffer) return new Uint8Array(data);
|
|
2016
|
+
return void 0;
|
|
2017
|
+
}
|
|
2018
|
+
function asIterable(data) {
|
|
2019
|
+
const d = data;
|
|
2020
|
+
if (d && typeof d[Symbol.asyncIterator] === "function") return data;
|
|
2021
|
+
if (d && typeof d.getReader === "function") return iterable(data);
|
|
2022
|
+
throw new InstaboxError(
|
|
2023
|
+
"files.write takes a string, a Uint8Array, an ArrayBuffer, a ReadableStream or an AsyncIterable of chunks",
|
|
2024
|
+
{ code: "bad_request" }
|
|
2025
|
+
);
|
|
2026
|
+
}
|
|
2027
|
+
function chunkBytes(chunk) {
|
|
2028
|
+
if (chunk instanceof Uint8Array) return chunk;
|
|
2029
|
+
if (typeof chunk === "string") return new TextEncoder().encode(chunk);
|
|
2030
|
+
if (chunk instanceof ArrayBuffer) return new Uint8Array(chunk);
|
|
2031
|
+
throw new InstaboxError("a stream given to files.write yielded something other than bytes or a string", {
|
|
2032
|
+
code: "bad_request"
|
|
2033
|
+
});
|
|
2034
|
+
}
|
|
2035
|
+
function sourceError(err) {
|
|
2036
|
+
if (err instanceof InstaboxError) return err;
|
|
2037
|
+
const msg = err?.message ?? String(err);
|
|
2038
|
+
return new InstaboxError(`reading the data to write failed: ${msg}`, { code: "source_error", cause: err });
|
|
2039
|
+
}
|
|
2040
|
+
async function collect(src, limit) {
|
|
2041
|
+
const parts = [];
|
|
2042
|
+
let n = 0;
|
|
2043
|
+
try {
|
|
2044
|
+
for await (const c of src) {
|
|
2045
|
+
const b = chunkBytes(c);
|
|
2046
|
+
n += b.length;
|
|
2047
|
+
if (n > limit) throw tooLargeForExec();
|
|
2048
|
+
parts.push(b);
|
|
2049
|
+
}
|
|
2050
|
+
} catch (err) {
|
|
2051
|
+
throw sourceError(err);
|
|
2052
|
+
}
|
|
2053
|
+
return concat(parts, n);
|
|
2054
|
+
}
|
|
2055
|
+
function concat(parts, n) {
|
|
2056
|
+
const out = new Uint8Array(n);
|
|
2057
|
+
let off = 0;
|
|
2058
|
+
for (const p of parts) {
|
|
2059
|
+
out.set(p, off);
|
|
2060
|
+
off += p.length;
|
|
2061
|
+
}
|
|
2062
|
+
return out;
|
|
2063
|
+
}
|
|
2064
|
+
async function* rechunk(src, size) {
|
|
2065
|
+
let buf = new Uint8Array(size);
|
|
2066
|
+
let n = 0;
|
|
2067
|
+
for await (const c of src) {
|
|
2068
|
+
let b = chunkBytes(c);
|
|
2069
|
+
while (b.length) {
|
|
2070
|
+
const take = Math.min(size - n, b.length);
|
|
2071
|
+
buf.set(b.subarray(0, take), n);
|
|
2072
|
+
n += take;
|
|
2073
|
+
b = b.subarray(take);
|
|
2074
|
+
if (n === size) {
|
|
2075
|
+
yield buf;
|
|
2076
|
+
buf = new Uint8Array(size);
|
|
2077
|
+
n = 0;
|
|
2078
|
+
}
|
|
2079
|
+
}
|
|
2080
|
+
}
|
|
2081
|
+
if (n) yield buf.subarray(0, n);
|
|
2082
|
+
}
|
|
2083
|
+
function oneChunk(bytes) {
|
|
2084
|
+
return new ReadableStream({
|
|
2085
|
+
start(c) {
|
|
2086
|
+
if (bytes.length) c.enqueue(bytes);
|
|
2087
|
+
c.close();
|
|
2088
|
+
}
|
|
2089
|
+
});
|
|
2090
|
+
}
|
|
2091
|
+
function iterable(stream) {
|
|
2092
|
+
const s = stream;
|
|
2093
|
+
if (typeof s[Symbol.asyncIterator] !== "function") {
|
|
2094
|
+
Object.defineProperty(s, Symbol.asyncIterator, {
|
|
2095
|
+
configurable: true,
|
|
2096
|
+
value: async function* () {
|
|
2097
|
+
const reader = stream.getReader();
|
|
2098
|
+
try {
|
|
2099
|
+
for (; ; ) {
|
|
2100
|
+
const { done, value } = await reader.read();
|
|
2101
|
+
if (done) return;
|
|
2102
|
+
yield value;
|
|
2103
|
+
}
|
|
2104
|
+
} finally {
|
|
2105
|
+
reader.releaseLock();
|
|
2106
|
+
}
|
|
2107
|
+
}
|
|
2108
|
+
});
|
|
2109
|
+
}
|
|
2110
|
+
return s;
|
|
2111
|
+
}
|
|
1047
2112
|
async function readBody(res, limit, path) {
|
|
1048
2113
|
const tooLarge = () => new InstaboxError(`${path} is larger than the ${limit}-byte limit of files.read`, { code: "file_too_large" });
|
|
1049
2114
|
const reader = res.body?.getReader();
|
|
@@ -1070,13 +2135,7 @@ async function readBody(res, limit, path) {
|
|
|
1070
2135
|
cause: err
|
|
1071
2136
|
});
|
|
1072
2137
|
}
|
|
1073
|
-
|
|
1074
|
-
let off = 0;
|
|
1075
|
-
for (const c of chunks) {
|
|
1076
|
-
out.set(c, off);
|
|
1077
|
-
off += c.length;
|
|
1078
|
-
}
|
|
1079
|
-
return out;
|
|
2138
|
+
return concat(chunks, n);
|
|
1080
2139
|
}
|
|
1081
2140
|
function routeMissing(err) {
|
|
1082
2141
|
if (!(err instanceof InstaboxError)) return false;
|
|
@@ -1089,6 +2148,14 @@ async function sha256Hex(bytes) {
|
|
|
1089
2148
|
const d = new Uint8Array(await subtle.digest("SHA-256", bytes));
|
|
1090
2149
|
return Array.from(d, (x) => x.toString(16).padStart(2, "0")).join("");
|
|
1091
2150
|
}
|
|
2151
|
+
async function sha256Stream() {
|
|
2152
|
+
try {
|
|
2153
|
+
const c = await import("node:crypto");
|
|
2154
|
+
return c.createHash("sha256");
|
|
2155
|
+
} catch {
|
|
2156
|
+
return void 0;
|
|
2157
|
+
}
|
|
2158
|
+
}
|
|
1092
2159
|
function writeError(result, path) {
|
|
1093
2160
|
if (result.exitCode === 21) return new InstaboxError(`is a directory: ${path}`, { code: "is_a_directory" });
|
|
1094
2161
|
return new CommandExitError(result);
|
|
@@ -1175,30 +2242,33 @@ var HttpClient = class {
|
|
|
1175
2242
|
async send(method, path, opts = {}) {
|
|
1176
2243
|
const isRead = method === "GET" || method === "HEAD";
|
|
1177
2244
|
const idempotent = opts.idempotent ?? !isRead;
|
|
1178
|
-
const retry = opts.retry ?? (isRead || idempotent);
|
|
1179
|
-
const
|
|
2245
|
+
const retry = opts.streamBody ? false : opts.retry ?? (isRead || idempotent);
|
|
2246
|
+
const headers2 = {
|
|
1180
2247
|
"X-API-Key": this.#apiKey,
|
|
1181
2248
|
Accept: opts.accept ?? "application/json",
|
|
1182
2249
|
...opts.headers
|
|
1183
2250
|
};
|
|
1184
|
-
if (idempotent)
|
|
2251
|
+
if (idempotent) headers2["Idempotency-Key"] = uuid();
|
|
1185
2252
|
let body;
|
|
1186
|
-
if (opts.
|
|
1187
|
-
|
|
2253
|
+
if (opts.streamBody !== void 0) {
|
|
2254
|
+
headers2["Content-Type"] = "application/octet-stream";
|
|
2255
|
+
body = opts.streamBody;
|
|
2256
|
+
} else if (opts.rawBody !== void 0) {
|
|
2257
|
+
headers2["Content-Type"] = "application/octet-stream";
|
|
1188
2258
|
body = opts.rawBody;
|
|
1189
2259
|
} else if (opts.body !== void 0) {
|
|
1190
|
-
|
|
2260
|
+
headers2["Content-Type"] = "application/json";
|
|
1191
2261
|
body = JSON.stringify(opts.body);
|
|
1192
2262
|
}
|
|
1193
2263
|
const where = this.#redact(`${method} ${path}`);
|
|
1194
2264
|
let url = this.apiUrl + path;
|
|
1195
2265
|
if (opts.query) {
|
|
1196
|
-
const
|
|
2266
|
+
const q2 = new URLSearchParams();
|
|
1197
2267
|
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)
|
|
2268
|
+
if (Array.isArray(v)) for (const item of v) q2.append(k, item);
|
|
2269
|
+
else if (v !== void 0) q2.set(k, String(v));
|
|
1200
2270
|
}
|
|
1201
|
-
const s =
|
|
2271
|
+
const s = q2.toString();
|
|
1202
2272
|
if (s) url += `?${s}`;
|
|
1203
2273
|
}
|
|
1204
2274
|
for (let attempt = 0; ; attempt++) {
|
|
@@ -1215,7 +2285,12 @@ var HttpClient = class {
|
|
|
1215
2285
|
else opts.signal?.addEventListener("abort", onAbort, { once: true });
|
|
1216
2286
|
let res;
|
|
1217
2287
|
try {
|
|
1218
|
-
|
|
2288
|
+
const init = { method, headers: headers2, body, signal: ctrl.signal };
|
|
2289
|
+
if (opts.streamBody !== void 0) {
|
|
2290
|
+
init.duplex = "half";
|
|
2291
|
+
init.redirect = "error";
|
|
2292
|
+
}
|
|
2293
|
+
res = await this.fetchImpl(url, init);
|
|
1219
2294
|
} catch (err) {
|
|
1220
2295
|
clearTimeout(timer);
|
|
1221
2296
|
opts.signal?.removeEventListener("abort", onAbort);
|
|
@@ -1411,7 +2486,7 @@ function toSeconds(ms, field) {
|
|
|
1411
2486
|
return s;
|
|
1412
2487
|
}
|
|
1413
2488
|
var METADATA_KEY = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
1414
|
-
var
|
|
2489
|
+
var enc3 = encodeURIComponent;
|
|
1415
2490
|
var Sandbox = class _Sandbox {
|
|
1416
2491
|
constructor(http, machine, opts = {}) {
|
|
1417
2492
|
this.http = http;
|
|
@@ -1419,6 +2494,7 @@ var Sandbox = class _Sandbox {
|
|
|
1419
2494
|
this.machine = machine;
|
|
1420
2495
|
this.commands = new Commands(http, machine.id, { ...opts.envs });
|
|
1421
2496
|
this.files = new Files(this.commands, http, machine.id);
|
|
2497
|
+
this.commands.stageStdin = (bytes, signal) => this.files.stageStdin(bytes, signal);
|
|
1422
2498
|
this.desktop = new Desktop(http, machine.id, this.commands, this.files);
|
|
1423
2499
|
}
|
|
1424
2500
|
http;
|
|
@@ -1509,12 +2585,12 @@ var Sandbox = class _Sandbox {
|
|
|
1509
2585
|
}
|
|
1510
2586
|
/** Fetches a snapshot by ID. Requires images:read. */
|
|
1511
2587
|
static async getSnapshot(snapshotId, opts = {}) {
|
|
1512
|
-
return new HttpClient(opts).request("GET", `/v1/snapshots/${
|
|
2588
|
+
return new HttpClient(opts).request("GET", `/v1/snapshots/${enc3(snapshotId)}`);
|
|
1513
2589
|
}
|
|
1514
2590
|
/** Deletes a snapshot. Returns false if absent. Requires images:delete. */
|
|
1515
2591
|
static async deleteSnapshot(snapshotId, opts = {}) {
|
|
1516
2592
|
try {
|
|
1517
|
-
await new HttpClient(opts).request("DELETE", `/v1/snapshots/${
|
|
2593
|
+
await new HttpClient(opts).request("DELETE", `/v1/snapshots/${enc3(snapshotId)}`);
|
|
1518
2594
|
return true;
|
|
1519
2595
|
} catch (err) {
|
|
1520
2596
|
if (err instanceof InstaboxError && err.status === 404 && err.code === "not_found") return false;
|
|
@@ -1529,7 +2605,7 @@ var Sandbox = class _Sandbox {
|
|
|
1529
2605
|
async createSnapshot(opts) {
|
|
1530
2606
|
await this.settle();
|
|
1531
2607
|
await this.untilSynced();
|
|
1532
|
-
return this.http.request("POST", `/v1/machines/${
|
|
2608
|
+
return this.http.request("POST", `/v1/machines/${enc3(this.sandboxId)}/snapshots`, { body: opts });
|
|
1533
2609
|
}
|
|
1534
2610
|
/** This sandbox's recent CPU and memory samples; see `Sandbox.getMetrics`. */
|
|
1535
2611
|
async getMetrics(opts = {}) {
|
|
@@ -1549,7 +2625,7 @@ var Sandbox = class _Sandbox {
|
|
|
1549
2625
|
* pause off. The setting stays across pause and resume.
|
|
1550
2626
|
*/
|
|
1551
2627
|
async setAutoSuspend(idleMs) {
|
|
1552
|
-
this.machine = await this.http.request("PATCH", `/v1/machines/${
|
|
2628
|
+
this.machine = await this.http.request("PATCH", `/v1/machines/${enc3(this.sandboxId)}`, {
|
|
1553
2629
|
body: { autoSuspendAfterSeconds: toIdleSeconds(idleMs) }
|
|
1554
2630
|
});
|
|
1555
2631
|
}
|
|
@@ -1563,7 +2639,7 @@ var Sandbox = class _Sandbox {
|
|
|
1563
2639
|
}
|
|
1564
2640
|
/** Replaces the sandbox's metadata (`{}` clears it). */
|
|
1565
2641
|
async setMetadata(metadata) {
|
|
1566
|
-
this.machine = await this.http.request("PATCH", `/v1/machines/${
|
|
2642
|
+
this.machine = await this.http.request("PATCH", `/v1/machines/${enc3(this.sandboxId)}`, {
|
|
1567
2643
|
body: { metadata }
|
|
1568
2644
|
});
|
|
1569
2645
|
}
|
|
@@ -1573,21 +2649,21 @@ var Sandbox = class _Sandbox {
|
|
|
1573
2649
|
* Throws `not_found` on a server without the Vault.
|
|
1574
2650
|
*/
|
|
1575
2651
|
async vault() {
|
|
1576
|
-
return this.http.request("GET", `/v1/machines/${
|
|
2652
|
+
return this.http.request("GET", `/v1/machines/${enc3(this.sandboxId)}/vault`);
|
|
1577
2653
|
}
|
|
1578
2654
|
/**
|
|
1579
2655
|
* Writes the account's current Vault items into the running sandbox now, the same write as after a boot,
|
|
1580
2656
|
* and returns its record (`error` set when the guest refused it). Requires machines:write.
|
|
1581
2657
|
*/
|
|
1582
2658
|
async pushVault() {
|
|
1583
|
-
return this.http.request("POST", `/v1/machines/${
|
|
2659
|
+
return this.http.request("POST", `/v1/machines/${enc3(this.sandboxId)}/vault`);
|
|
1584
2660
|
}
|
|
1585
2661
|
/**
|
|
1586
2662
|
* Turns the Vault off for this sandbox, for good, in any state: its next boot, resume or push removes
|
|
1587
2663
|
* what the Vault wrote and nothing is written again. Requires machines:write.
|
|
1588
2664
|
*/
|
|
1589
2665
|
async disableVault() {
|
|
1590
|
-
this.machine = await this.http.request("PATCH", `/v1/machines/${
|
|
2666
|
+
this.machine = await this.http.request("PATCH", `/v1/machines/${enc3(this.sandboxId)}`, {
|
|
1591
2667
|
body: { vault: false }
|
|
1592
2668
|
});
|
|
1593
2669
|
}
|
|
@@ -1634,7 +2710,7 @@ var Sandbox = class _Sandbox {
|
|
|
1634
2710
|
}
|
|
1635
2711
|
body.ttlSeconds = opts.ttlSeconds;
|
|
1636
2712
|
}
|
|
1637
|
-
const c = await this.http.request("POST", `/v1/machines/${
|
|
2713
|
+
const c = await this.http.request("POST", `/v1/machines/${enc3(this.sandboxId)}/connections`, { body });
|
|
1638
2714
|
return {
|
|
1639
2715
|
host: c.host,
|
|
1640
2716
|
port: c.port,
|
|
@@ -1653,7 +2729,7 @@ var Sandbox = class _Sandbox {
|
|
|
1653
2729
|
async settle(refresh = true) {
|
|
1654
2730
|
if (refresh) this.machine = await getMachine(this.http, this.sandboxId);
|
|
1655
2731
|
if (this.machine.operationId) {
|
|
1656
|
-
const op = await this.http.request("GET", `/v1/operations/${
|
|
2732
|
+
const op = await this.http.request("GET", `/v1/operations/${enc3(this.machine.operationId)}`);
|
|
1657
2733
|
await this.http.waitForOperation(op).catch(() => {
|
|
1658
2734
|
});
|
|
1659
2735
|
this.machine = await getMachine(this.http, this.sandboxId);
|
|
@@ -1681,29 +2757,29 @@ var Sandbox = class _Sandbox {
|
|
|
1681
2757
|
}
|
|
1682
2758
|
}
|
|
1683
2759
|
async mutate(method, action) {
|
|
1684
|
-
const op = await this.http.request(method, `/v1/machines/${
|
|
2760
|
+
const op = await this.http.request(method, `/v1/machines/${enc3(this.sandboxId)}/${action}`);
|
|
1685
2761
|
await this.http.waitForOperation(op);
|
|
1686
2762
|
this.machine = await getMachine(this.http, this.sandboxId);
|
|
1687
2763
|
}
|
|
1688
2764
|
};
|
|
1689
2765
|
async function getMachine(http, id) {
|
|
1690
|
-
return http.request("GET", `/v1/machines/${
|
|
2766
|
+
return http.request("GET", `/v1/machines/${enc3(id)}`);
|
|
1691
2767
|
}
|
|
1692
2768
|
async function getMetrics(http, id, opts) {
|
|
1693
|
-
const out = await http.request("GET", `/v1/machines/${
|
|
2769
|
+
const out = await http.request("GET", `/v1/machines/${enc3(id)}/metrics`, {
|
|
1694
2770
|
query: { since: opts.since?.toISOString() }
|
|
1695
2771
|
});
|
|
1696
2772
|
return out.metrics.map((s) => ({ ...s, timestamp: new Date(s.timestamp) }));
|
|
1697
2773
|
}
|
|
1698
2774
|
async function getUsage(http, id, opts) {
|
|
1699
|
-
const u = await http.request("GET", `/v1/machines/${
|
|
2775
|
+
const u = await http.request("GET", `/v1/machines/${enc3(id)}/usage`, {
|
|
1700
2776
|
query: { from: opts.from?.toISOString(), to: opts.to?.toISOString() }
|
|
1701
2777
|
});
|
|
1702
2778
|
return { ...u, from: new Date(u.from), to: new Date(u.to) };
|
|
1703
2779
|
}
|
|
1704
2780
|
async function killMachine(http, id) {
|
|
1705
2781
|
try {
|
|
1706
|
-
const op = await http.request("DELETE", `/v1/machines/${
|
|
2782
|
+
const op = await http.request("DELETE", `/v1/machines/${enc3(id)}`, {
|
|
1707
2783
|
headers: { "X-Confirm-Delete": id }
|
|
1708
2784
|
});
|
|
1709
2785
|
await http.waitForOperation(op);
|
|
@@ -1766,6 +2842,7 @@ export {
|
|
|
1766
2842
|
LIMIT_CODES,
|
|
1767
2843
|
MAX_FILE_BYTES,
|
|
1768
2844
|
MAX_STDIN_BYTES,
|
|
2845
|
+
MAX_UPLOAD_BYTES,
|
|
1769
2846
|
Sandbox,
|
|
1770
2847
|
isLimitCode
|
|
1771
2848
|
};
|