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