@sandboxrouter/sdk 0.20.1 → 0.21.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 +29 -29
- package/dist/catalog.d.ts +34 -0
- package/dist/catalog.js +53 -1
- package/dist/cli-terminal.d.ts +15 -0
- package/dist/cli-terminal.js +52 -0
- package/dist/cli.js +33 -2
- package/dist/conformance.d.ts +22 -4
- package/dist/conformance.js +48 -6
- package/dist/gate-scripts.d.ts +28 -0
- package/dist/gate-scripts.js +482 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +5 -0
- package/dist/leaderboard.d.ts +12 -0
- package/dist/leaderboard.js +10 -0
- package/dist/lifecycle.d.ts +158 -0
- package/dist/lifecycle.js +171 -0
- package/dist/preview.d.ts +104 -0
- package/dist/preview.js +209 -0
- package/dist/providers/blaxel.js +52 -0
- package/dist/providers/daytona.js +38 -0
- package/dist/providers/e2b.d.ts +23 -1
- package/dist/providers/e2b.js +29 -1
- package/dist/providers/modal.js +18 -0
- package/dist/providers/tensorlake.js +11 -0
- package/dist/published.js +48 -216
- package/dist/recommend.d.ts +20 -3
- package/dist/recommend.js +33 -11
- package/dist/router.d.ts +84 -1
- package/dist/router.js +145 -3
- package/dist/spawn.d.ts +116 -0
- package/dist/spawn.js +467 -0
- package/dist/terminal-helper.d.ts +34 -0
- package/dist/terminal-helper.js +429 -0
- package/dist/terminal.d.ts +79 -0
- package/dist/terminal.js +552 -0
- package/dist/types.d.ts +48 -0
- package/dist/util.d.ts +7 -0
- package/dist/util.js +16 -1
- package/package.json +1 -1
|
@@ -0,0 +1,482 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The preview gate: a small reverse proxy that runs inside the sandbox, in front of one port of the
|
|
3
|
+
* app, and lets a request through only when it carries the link's token. Two versions that behave
|
|
4
|
+
* the same, one for `node` and one for `python3`, standard library only, so it runs on whatever
|
|
5
|
+
* the image has. `preview.ts` starts it and says what it is for; the rules it keeps are below.
|
|
6
|
+
*
|
|
7
|
+
* gate <listen ports, comma separated, 0 = any free> <app port> <seconds to live> <sha256 of the token, hex, or "-"> <its folder>
|
|
8
|
+
*
|
|
9
|
+
* - It only ever connects to 127.0.0.1:<app port>.
|
|
10
|
+
* - A request is let through when the gate's cookie holds the token, or (not for a page a browser
|
|
11
|
+
* opens: see next) when `?sr_token=` does. The token is compared as a SHA-256 in constant time;
|
|
12
|
+
* the gate is given only that hash, never the token.
|
|
13
|
+
* - A GET or HEAD that brings a valid `?sr_token=` and no cookie is answered with a redirect to the
|
|
14
|
+
* same path without the token, and the cookie (HttpOnly, Secure, SameSite=Lax, Path=/). The
|
|
15
|
+
* redirect is always to a path on the same host.
|
|
16
|
+
* - The token parameter and the gate's cookie are taken off before the request goes to the app.
|
|
17
|
+
* - One request per connection: the gate reads one request head (32 KB at most), forwards exactly
|
|
18
|
+
* its body (`Content-Length`; a chunked request body is refused with 411) and marks both sides
|
|
19
|
+
* `Connection: close`. An upgraded connection (WebSocket) is one client's and is piped until it ends.
|
|
20
|
+
* - Responses are passed on as they arrive, never held back or stored.
|
|
21
|
+
* - After the expiry every open connection is cut and every request gets 410. The gate leaves when
|
|
22
|
+
* its folder is removed (`revoke()`), and ten minutes after the expiry.
|
|
23
|
+
* - Nothing about a request is written anywhere.
|
|
24
|
+
*
|
|
25
|
+
* Neither script may contain a backtick or a dollar-brace: they are raw template strings.
|
|
26
|
+
*/
|
|
27
|
+
export const GATE_NODE = String.raw `"use strict";
|
|
28
|
+
var net = require("net"), fs = require("fs"), crypto = require("crypto");
|
|
29
|
+
var a = process.argv.slice(2);
|
|
30
|
+
var PORTS = a[0].split(",").map(Number), TARGET = Number(a[1]), TTL = Number(a[2]), HASH = a[3], DIR = a[4];
|
|
31
|
+
var OPEN = HASH === "-";
|
|
32
|
+
var WANT = OPEN ? null : Buffer.from(HASH, "hex");
|
|
33
|
+
var NOW = function () { return Date.now(); };
|
|
34
|
+
var exp = NOW() + TTL * 1000, expired = false, leaveAt = 0;
|
|
35
|
+
var MAX_HEAD = 32768, COOKIE = "";
|
|
36
|
+
var socks = new Set();
|
|
37
|
+
var NAME = /^[!#$%&'*+.^_|~0-9A-Za-z-]+$/;
|
|
38
|
+
var TOKEN = /^[A-Za-z0-9_-]{16,256}$/;
|
|
39
|
+
|
|
40
|
+
function ok(tok) {
|
|
41
|
+
if (OPEN) return true;
|
|
42
|
+
if (typeof tok !== "string" || !TOKEN.test(tok)) tok = "";
|
|
43
|
+
return crypto.timingSafeEqual(crypto.createHash("sha256").update(tok, "latin1").digest(), WANT);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function reply(s, code, reason, extra, body) {
|
|
47
|
+
var b = Buffer.from(body || "");
|
|
48
|
+
var head = "HTTP/1.1 " + code + " " + reason + "\r\n" + (extra || "") +
|
|
49
|
+
"Content-Type: text/plain; charset=utf-8\r\nContent-Length: " + b.length +
|
|
50
|
+
"\r\nCache-Control: no-store\r\nReferrer-Policy: no-referrer\r\nX-Content-Type-Options: nosniff\r\nConnection: close\r\n\r\n";
|
|
51
|
+
s.removeAllListeners("data");
|
|
52
|
+
s.on("data", function () {});
|
|
53
|
+
s.resume();
|
|
54
|
+
s.end(Buffer.concat([Buffer.from(head, "latin1"), b]));
|
|
55
|
+
setTimeout(function () { s.destroy(); }, 5000).unref();
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function onConn(c) {
|
|
59
|
+
socks.add(c);
|
|
60
|
+
c.on("close", function () { socks.delete(c); });
|
|
61
|
+
c.on("error", function () {});
|
|
62
|
+
c.setTimeout(30000, function () { c.destroy(); });
|
|
63
|
+
var buf = Buffer.alloc(0);
|
|
64
|
+
function onData(d) {
|
|
65
|
+
buf = buf.length ? Buffer.concat([buf, d]) : d;
|
|
66
|
+
var i = buf.indexOf("\r\n\r\n");
|
|
67
|
+
if (i < 0 ? buf.length > MAX_HEAD : i > MAX_HEAD) {
|
|
68
|
+
c.removeListener("data", onData);
|
|
69
|
+
return reply(c, 431, "Request Header Fields Too Large", "", "The request headers are too large.\n");
|
|
70
|
+
}
|
|
71
|
+
if (i < 0) return;
|
|
72
|
+
c.removeListener("data", onData);
|
|
73
|
+
c.pause();
|
|
74
|
+
c.setTimeout(0);
|
|
75
|
+
handle(c, buf.slice(0, i).toString("latin1"), buf.slice(i + 4));
|
|
76
|
+
}
|
|
77
|
+
c.on("data", onData);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function handle(c, head, rest) {
|
|
81
|
+
var bad = function () { reply(c, 400, "Bad Request", "", "Bad request.\n"); };
|
|
82
|
+
var lines = head.split("\r\n");
|
|
83
|
+
var m = /^([A-Z]+) (\S+) (HTTP\/1\.[01])$/.exec(lines[0]);
|
|
84
|
+
if (!m || m[2].charAt(0) !== "/" || lines.length > 201) return bad();
|
|
85
|
+
if (NOW() >= exp) return reply(c, 410, "Gone", "", "This preview link has expired.\n");
|
|
86
|
+
var hs = [], k, j, n;
|
|
87
|
+
for (k = 1; k < lines.length; k++) {
|
|
88
|
+
j = lines[k].indexOf(":");
|
|
89
|
+
if (j <= 0 || !NAME.test(lines[k].slice(0, j)) || /[\0\r\n]/.test(lines[k])) return bad();
|
|
90
|
+
hs.push([lines[k].slice(0, j), lines[k].slice(j + 1).trim(), lines[k].slice(0, j).toLowerCase()]);
|
|
91
|
+
}
|
|
92
|
+
var q = m[2].indexOf("?");
|
|
93
|
+
var pairs = q < 0 ? [] : m[2].slice(q + 1).split("&"), keep = [], given = null;
|
|
94
|
+
for (k = 0; k < pairs.length; k++) {
|
|
95
|
+
if (pairs[k] === "sr_token" || pairs[k].slice(0, 9) === "sr_token=") { if (given === null) given = pairs[k].slice(9); }
|
|
96
|
+
else keep.push(pairs[k]);
|
|
97
|
+
}
|
|
98
|
+
var target = (q < 0 ? m[2] : m[2].slice(0, q)) + (keep.length ? "?" + keep.join("&") : "");
|
|
99
|
+
var cookieTok = null, cookieKeep = [], up = false, hasUp = false, te = false, cls = [];
|
|
100
|
+
for (k = 0; k < hs.length; k++) {
|
|
101
|
+
n = hs[k][2];
|
|
102
|
+
if (n === "cookie") {
|
|
103
|
+
hs[k][1].split(";").forEach(function (part) {
|
|
104
|
+
var t = part.trim();
|
|
105
|
+
if (!t) return;
|
|
106
|
+
if (t.slice(0, COOKIE.length + 1) === COOKIE + "=") { if (cookieTok === null) cookieTok = t.slice(COOKIE.length + 1); }
|
|
107
|
+
else cookieKeep.push(t);
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
if (n === "upgrade") hasUp = true;
|
|
111
|
+
if (n === "connection" && /(^|,)\s*upgrade\s*(,|$)/i.test(hs[k][1])) up = true;
|
|
112
|
+
if (n === "transfer-encoding") te = true;
|
|
113
|
+
if (n === "content-length") cls.push(hs[k][1]);
|
|
114
|
+
}
|
|
115
|
+
up = up && hasUp;
|
|
116
|
+
var byCookie = ok(cookieTok), byParam = ok(given === null ? "" : given);
|
|
117
|
+
if (!byCookie && !byParam) return reply(c, 401, "Unauthorized", "", "This preview is private. Open it with the link you were given.\n");
|
|
118
|
+
if (!byCookie && (m[1] === "GET" || m[1] === "HEAD") && !up) {
|
|
119
|
+
var left0 = Math.max(1, Math.ceil((exp - NOW()) / 1000));
|
|
120
|
+
return reply(c, 302, "Found",
|
|
121
|
+
"Location: /" + target.replace(/^[\/\\]+/, "") + "\r\nSet-Cookie: " + COOKIE + "=" + given + "; Max-Age=" + left0 + "; Path=/; HttpOnly; Secure; SameSite=Lax\r\n", "");
|
|
122
|
+
}
|
|
123
|
+
if (te) return reply(c, 411, "Length Required", "", "Send the request body with a Content-Length.\n");
|
|
124
|
+
var len = 0;
|
|
125
|
+
if (cls.length) {
|
|
126
|
+
for (k = 0; k < cls.length; k++) if (!/^\d{1,15}$/.test(cls[k]) || cls[k] !== cls[0]) return bad();
|
|
127
|
+
len = Number(cls[0]);
|
|
128
|
+
}
|
|
129
|
+
var DROP = { cookie: 1, connection: 1, "keep-alive": 1, "proxy-connection": 1, "content-length": 1 };
|
|
130
|
+
var out = m[1] + " " + target + " " + m[3] + "\r\n";
|
|
131
|
+
for (k = 0; k < hs.length; k++) {
|
|
132
|
+
if (DROP[hs[k][2]] || (!up && hs[k][2] === "upgrade")) continue;
|
|
133
|
+
out += hs[k][0] + ": " + hs[k][1] + "\r\n";
|
|
134
|
+
}
|
|
135
|
+
if (cookieKeep.length) out += "Cookie: " + cookieKeep.join("; ") + "\r\n";
|
|
136
|
+
if (cls.length) out += "Content-Length: " + len + "\r\n";
|
|
137
|
+
out += up ? "Connection: Upgrade\r\n\r\n" : "Connection: close\r\n\r\n";
|
|
138
|
+
|
|
139
|
+
var left = up ? Infinity : len, started = false, sent = false, raw = false, rb = Buffer.alloc(0);
|
|
140
|
+
var u = net.connect({ port: TARGET, host: "127.0.0.1" });
|
|
141
|
+
socks.add(u);
|
|
142
|
+
var toClient = function (d) { sent = true; if (!c.write(d)) { u.pause(); c.once("drain", function () { u.resume(); }); } };
|
|
143
|
+
var drop = function () { c.destroy(); u.destroy(); };
|
|
144
|
+
u.on("error", function () {
|
|
145
|
+
if (!started) reply(c, 502, "Bad Gateway", "", "Nothing answers on 127.0.0.1:" + TARGET + " in the sandbox.\n");
|
|
146
|
+
else if (!sent) reply(c, 502, "Bad Gateway", "", "The app closed the connection.\n");
|
|
147
|
+
else c.destroy();
|
|
148
|
+
});
|
|
149
|
+
u.on("close", function () {
|
|
150
|
+
socks.delete(u);
|
|
151
|
+
if (started && !sent && !c.destroyed) reply(c, 502, "Bad Gateway", "", "The app closed the connection.\n");
|
|
152
|
+
else c.end();
|
|
153
|
+
});
|
|
154
|
+
c.on("close", function () { u.destroy(); });
|
|
155
|
+
c.on("end", function () { u.destroy(); });
|
|
156
|
+
u.on("connect", function () {
|
|
157
|
+
started = true;
|
|
158
|
+
u.write(Buffer.from(out, "latin1"));
|
|
159
|
+
var feed = function (d) {
|
|
160
|
+
if (left <= 0) return;
|
|
161
|
+
if (d.length > left) d = d.slice(0, left);
|
|
162
|
+
left -= d.length;
|
|
163
|
+
if (!u.write(d)) { c.pause(); u.once("drain", function () { c.resume(); }); }
|
|
164
|
+
};
|
|
165
|
+
if (rest.length) feed(rest);
|
|
166
|
+
c.on("data", feed);
|
|
167
|
+
c.resume();
|
|
168
|
+
});
|
|
169
|
+
u.on("data", function (d) {
|
|
170
|
+
if (raw) return toClient(d);
|
|
171
|
+
rb = rb.length ? Buffer.concat([rb, d]) : d;
|
|
172
|
+
for (;;) {
|
|
173
|
+
var i = rb.indexOf("\r\n\r\n");
|
|
174
|
+
if (i < 0) {
|
|
175
|
+
if (rb.length > 65536) { if (sent) drop(); else { u.destroy(); reply(c, 502, "Bad Gateway", "", "The app's response headers are too large.\n"); } }
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
var rl = rb.slice(0, i).toString("latin1").split("\r\n");
|
|
179
|
+
var sm = /^HTTP\/1\.[01] (\d{3})/.exec(rl[0]);
|
|
180
|
+
if (!sm) { if (sent) drop(); else { u.destroy(); reply(c, 502, "Bad Gateway", "", "The app did not answer with HTTP.\n"); } return; }
|
|
181
|
+
var code = Number(sm[1]);
|
|
182
|
+
if (code === 101) {
|
|
183
|
+
if (!up) return drop();
|
|
184
|
+
raw = true;
|
|
185
|
+
return toClient(rb);
|
|
186
|
+
}
|
|
187
|
+
if (code < 200) { toClient(rb.slice(0, i + 4)); rb = rb.slice(i + 4); continue; }
|
|
188
|
+
// Not upgraded: nothing more of this connection goes to the app.
|
|
189
|
+
if (up) left = 0;
|
|
190
|
+
var o = rl[0] + "\r\n";
|
|
191
|
+
for (var x = 1; x < rl.length; x++) {
|
|
192
|
+
var hn = rl[x].slice(0, Math.max(0, rl[x].indexOf(":"))).toLowerCase();
|
|
193
|
+
if (hn !== "connection" && hn !== "keep-alive") o += rl[x] + "\r\n";
|
|
194
|
+
}
|
|
195
|
+
raw = true;
|
|
196
|
+
return toClient(Buffer.concat([Buffer.from(o + "Connection: close\r\n\r\n", "latin1"), rb.slice(i + 4)]));
|
|
197
|
+
}
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
setInterval(function () {
|
|
202
|
+
var now = NOW();
|
|
203
|
+
if (!fs.existsSync(DIR)) process.exit(0);
|
|
204
|
+
try {
|
|
205
|
+
var e = Number(String(fs.readFileSync(DIR + "/exp")).trim()) * 1000;
|
|
206
|
+
if (e > 0 && e < exp) exp = e;
|
|
207
|
+
} catch (err) {}
|
|
208
|
+
if (!expired && now >= exp) {
|
|
209
|
+
expired = true;
|
|
210
|
+
leaveAt = now + 600000;
|
|
211
|
+
socks.forEach(function (s) { s.destroy(); });
|
|
212
|
+
}
|
|
213
|
+
if (expired && now >= leaveAt) process.exit(0);
|
|
214
|
+
}, 500);
|
|
215
|
+
|
|
216
|
+
(function listen(i) {
|
|
217
|
+
if (i >= PORTS.length) { process.stdout.write("SRGATE fail\n"); return setTimeout(function () { process.exit(3); }, 200); }
|
|
218
|
+
var server = net.createServer(onConn);
|
|
219
|
+
server.once("error", function () { listen(i + 1); });
|
|
220
|
+
server.listen(PORTS[i], "0.0.0.0", function () {
|
|
221
|
+
server.removeAllListeners("error");
|
|
222
|
+
server.on("error", function () {});
|
|
223
|
+
COOKIE = "sr_gate_" + server.address().port;
|
|
224
|
+
process.stdout.write("SRGATE port=" + server.address().port + "\n");
|
|
225
|
+
});
|
|
226
|
+
})(0);
|
|
227
|
+
`;
|
|
228
|
+
export const GATE_PYTHON = String.raw `import asyncio, hashlib, hmac, os, re, sys, time
|
|
229
|
+
|
|
230
|
+
PORTS = [int(x) for x in sys.argv[1].split(",")]
|
|
231
|
+
TARGET = int(sys.argv[2])
|
|
232
|
+
TTL = float(sys.argv[3])
|
|
233
|
+
HASH = sys.argv[4]
|
|
234
|
+
DIR = sys.argv[5]
|
|
235
|
+
OPEN = HASH == "-"
|
|
236
|
+
WANT = b"" if OPEN else bytes.fromhex(HASH)
|
|
237
|
+
S = {"exp": time.time() + TTL, "expired": False, "leave": 0.0, "cookie": ""}
|
|
238
|
+
MAX_HEAD = 32768
|
|
239
|
+
CONNS = set()
|
|
240
|
+
NAME = re.compile(r"[!#$%&'*+.^_|~0-9A-Za-z-]+")
|
|
241
|
+
TOKEN = re.compile(r"[A-Za-z0-9_-]{16,256}")
|
|
242
|
+
REQ = re.compile(r"([A-Z]+) (\S+) (HTTP/1\.[01])")
|
|
243
|
+
UPG = re.compile(r"(^|,)\s*upgrade\s*(,|$)", re.I)
|
|
244
|
+
DROP = ("cookie", "connection", "keep-alive", "proxy-connection", "content-length")
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def ok(tok):
|
|
248
|
+
if OPEN:
|
|
249
|
+
return True
|
|
250
|
+
if not isinstance(tok, str) or not TOKEN.fullmatch(tok):
|
|
251
|
+
tok = ""
|
|
252
|
+
return hmac.compare_digest(hashlib.sha256(tok.encode("latin1")).digest(), WANT)
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
async def reply(w, code, reason, extra, body):
|
|
256
|
+
b = body.encode("utf-8")
|
|
257
|
+
head = ("HTTP/1.1 %d %s\r\n%sContent-Type: text/plain; charset=utf-8\r\nContent-Length: %d\r\n"
|
|
258
|
+
"Cache-Control: no-store\r\nReferrer-Policy: no-referrer\r\nX-Content-Type-Options: nosniff\r\nConnection: close\r\n\r\n") % (code, reason, extra, len(b))
|
|
259
|
+
try:
|
|
260
|
+
w.write(head.encode("latin1") + b)
|
|
261
|
+
await w.drain()
|
|
262
|
+
except Exception:
|
|
263
|
+
pass
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def shut(w):
|
|
267
|
+
try:
|
|
268
|
+
w.transport.abort()
|
|
269
|
+
except Exception:
|
|
270
|
+
pass
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
async def conn(r, w):
|
|
274
|
+
CONNS.add(w)
|
|
275
|
+
try:
|
|
276
|
+
await serve(r, w)
|
|
277
|
+
except Exception:
|
|
278
|
+
pass
|
|
279
|
+
finally:
|
|
280
|
+
CONNS.discard(w)
|
|
281
|
+
try:
|
|
282
|
+
w.close()
|
|
283
|
+
except Exception:
|
|
284
|
+
pass
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
async def serve(r, w):
|
|
288
|
+
try:
|
|
289
|
+
raw = await asyncio.wait_for(r.readuntil(b"\r\n\r\n"), 30)
|
|
290
|
+
except asyncio.LimitOverrunError:
|
|
291
|
+
return await reply(w, 431, "Request Header Fields Too Large", "", "The request headers are too large.\n")
|
|
292
|
+
except Exception:
|
|
293
|
+
return
|
|
294
|
+
lines = raw[:-4].decode("latin1").split("\r\n")
|
|
295
|
+
m = REQ.fullmatch(lines[0])
|
|
296
|
+
if not m or not m.group(2).startswith("/") or len(lines) > 201:
|
|
297
|
+
return await reply(w, 400, "Bad Request", "", "Bad request.\n")
|
|
298
|
+
if time.time() >= S["exp"]:
|
|
299
|
+
return await reply(w, 410, "Gone", "", "This preview link has expired.\n")
|
|
300
|
+
method, full, version = m.group(1), m.group(2), m.group(3)
|
|
301
|
+
hs = []
|
|
302
|
+
for line in lines[1:]:
|
|
303
|
+
j = line.find(":")
|
|
304
|
+
if j <= 0 or not NAME.fullmatch(line[:j]) or "\0" in line or "\r" in line or "\n" in line:
|
|
305
|
+
return await reply(w, 400, "Bad Request", "", "Bad request.\n")
|
|
306
|
+
hs.append((line[:j], line[j + 1:].strip(), line[:j].lower()))
|
|
307
|
+
q = full.find("?")
|
|
308
|
+
keep, given = [], None
|
|
309
|
+
for p in ([] if q < 0 else full[q + 1:].split("&")):
|
|
310
|
+
if p == "sr_token" or p.startswith("sr_token="):
|
|
311
|
+
if given is None:
|
|
312
|
+
given = p[9:]
|
|
313
|
+
else:
|
|
314
|
+
keep.append(p)
|
|
315
|
+
target = (full if q < 0 else full[:q]) + ("?" + "&".join(keep) if keep else "")
|
|
316
|
+
cookie = S["cookie"]
|
|
317
|
+
cookie_tok, cookie_keep, up, has_up, te, cls = None, [], False, False, False, []
|
|
318
|
+
for (name, value, n) in hs:
|
|
319
|
+
if n == "cookie":
|
|
320
|
+
for part in value.split(";"):
|
|
321
|
+
t = part.strip()
|
|
322
|
+
if not t:
|
|
323
|
+
continue
|
|
324
|
+
if t.startswith(cookie + "="):
|
|
325
|
+
if cookie_tok is None:
|
|
326
|
+
cookie_tok = t[len(cookie) + 1:]
|
|
327
|
+
else:
|
|
328
|
+
cookie_keep.append(t)
|
|
329
|
+
if n == "upgrade":
|
|
330
|
+
has_up = True
|
|
331
|
+
if n == "connection" and UPG.search(value):
|
|
332
|
+
up = True
|
|
333
|
+
if n == "transfer-encoding":
|
|
334
|
+
te = True
|
|
335
|
+
if n == "content-length":
|
|
336
|
+
cls.append(value)
|
|
337
|
+
up = up and has_up
|
|
338
|
+
by_cookie = ok(cookie_tok)
|
|
339
|
+
by_param = ok("" if given is None else given)
|
|
340
|
+
if not by_cookie and not by_param:
|
|
341
|
+
return await reply(w, 401, "Unauthorized", "", "This preview is private. Open it with the link you were given.\n")
|
|
342
|
+
if not by_cookie and method in ("GET", "HEAD") and not up:
|
|
343
|
+
left0 = max(1, int(S["exp"] - time.time() + 0.999))
|
|
344
|
+
return await reply(w, 302, "Found", "Location: /%s\r\nSet-Cookie: %s=%s; Max-Age=%d; Path=/; HttpOnly; Secure; SameSite=Lax\r\n" % (target.lstrip("/\\"), cookie, given, left0), "")
|
|
345
|
+
if te:
|
|
346
|
+
return await reply(w, 411, "Length Required", "", "Send the request body with a Content-Length.\n")
|
|
347
|
+
length = 0
|
|
348
|
+
if cls:
|
|
349
|
+
for v in cls:
|
|
350
|
+
if not re.fullmatch(r"[0-9]{1,15}", v) or v != cls[0]:
|
|
351
|
+
return await reply(w, 400, "Bad Request", "", "Bad request.\n")
|
|
352
|
+
length = int(cls[0])
|
|
353
|
+
out = "%s %s %s\r\n" % (method, target, version)
|
|
354
|
+
for (name, value, n) in hs:
|
|
355
|
+
if n in DROP or (not up and n == "upgrade"):
|
|
356
|
+
continue
|
|
357
|
+
out += "%s: %s\r\n" % (name, value)
|
|
358
|
+
if cookie_keep:
|
|
359
|
+
out += "Cookie: %s\r\n" % "; ".join(cookie_keep)
|
|
360
|
+
if cls:
|
|
361
|
+
out += "Content-Length: %d\r\n" % length
|
|
362
|
+
out += "Connection: Upgrade\r\n\r\n" if up else "Connection: close\r\n\r\n"
|
|
363
|
+
try:
|
|
364
|
+
ur, uw = await asyncio.open_connection("127.0.0.1", TARGET, limit=65536)
|
|
365
|
+
except Exception:
|
|
366
|
+
return await reply(w, 502, "Bad Gateway", "", "Nothing answers on 127.0.0.1:%d in the sandbox.\n" % TARGET)
|
|
367
|
+
CONNS.add(uw)
|
|
368
|
+
st = {"left": float("inf") if up else length, "sent": False}
|
|
369
|
+
|
|
370
|
+
async def c2u():
|
|
371
|
+
# Exactly the body goes to the app; what a client sends after it is read and dropped.
|
|
372
|
+
while True:
|
|
373
|
+
d = await r.read(65536)
|
|
374
|
+
if not d:
|
|
375
|
+
return
|
|
376
|
+
if st["left"] <= 0:
|
|
377
|
+
continue
|
|
378
|
+
if len(d) > st["left"]:
|
|
379
|
+
d = d[:int(st["left"])]
|
|
380
|
+
st["left"] -= len(d)
|
|
381
|
+
uw.write(d)
|
|
382
|
+
await uw.drain()
|
|
383
|
+
|
|
384
|
+
async def u2c():
|
|
385
|
+
while True:
|
|
386
|
+
try:
|
|
387
|
+
h = await ur.readuntil(b"\r\n\r\n")
|
|
388
|
+
except Exception:
|
|
389
|
+
if not st["sent"]:
|
|
390
|
+
await reply(w, 502, "Bad Gateway", "", "The app closed the connection.\n")
|
|
391
|
+
return
|
|
392
|
+
rl = h[:-4].decode("latin1").split("\r\n")
|
|
393
|
+
sm = re.match(r"HTTP/1\.[01] ([0-9]{3})", rl[0])
|
|
394
|
+
if not sm:
|
|
395
|
+
if not st["sent"]:
|
|
396
|
+
await reply(w, 502, "Bad Gateway", "", "The app did not answer with HTTP.\n")
|
|
397
|
+
return
|
|
398
|
+
code = int(sm.group(1))
|
|
399
|
+
if code == 101:
|
|
400
|
+
if not up:
|
|
401
|
+
return
|
|
402
|
+
w.write(h)
|
|
403
|
+
break
|
|
404
|
+
if code < 200:
|
|
405
|
+
st["sent"] = True
|
|
406
|
+
w.write(h)
|
|
407
|
+
await w.drain()
|
|
408
|
+
continue
|
|
409
|
+
if up:
|
|
410
|
+
st["left"] = 0
|
|
411
|
+
o = rl[0] + "\r\n"
|
|
412
|
+
for x in rl[1:]:
|
|
413
|
+
hn = x[:max(0, x.find(":"))].lower()
|
|
414
|
+
if hn not in ("connection", "keep-alive"):
|
|
415
|
+
o += x + "\r\n"
|
|
416
|
+
w.write((o + "Connection: close\r\n\r\n").encode("latin1"))
|
|
417
|
+
break
|
|
418
|
+
st["sent"] = True
|
|
419
|
+
await w.drain()
|
|
420
|
+
while True:
|
|
421
|
+
d = await ur.read(65536)
|
|
422
|
+
if not d:
|
|
423
|
+
return
|
|
424
|
+
w.write(d)
|
|
425
|
+
await w.drain()
|
|
426
|
+
|
|
427
|
+
try:
|
|
428
|
+
uw.write(out.encode("latin1"))
|
|
429
|
+
await uw.drain()
|
|
430
|
+
tasks = [asyncio.ensure_future(c2u()), asyncio.ensure_future(u2c())]
|
|
431
|
+
await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
|
|
432
|
+
for t in tasks:
|
|
433
|
+
t.cancel()
|
|
434
|
+
try:
|
|
435
|
+
await asyncio.wait_for(w.drain(), 5)
|
|
436
|
+
except Exception:
|
|
437
|
+
pass
|
|
438
|
+
finally:
|
|
439
|
+
CONNS.discard(uw)
|
|
440
|
+
shut(uw)
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
async def watch():
|
|
444
|
+
while True:
|
|
445
|
+
await asyncio.sleep(0.5)
|
|
446
|
+
now = time.time()
|
|
447
|
+
if not os.path.isdir(DIR):
|
|
448
|
+
os._exit(0)
|
|
449
|
+
try:
|
|
450
|
+
with open(DIR + "/exp") as f:
|
|
451
|
+
e = float(f.read().strip())
|
|
452
|
+
if 0 < e < S["exp"]:
|
|
453
|
+
S["exp"] = e
|
|
454
|
+
except Exception:
|
|
455
|
+
pass
|
|
456
|
+
if not S["expired"] and now >= S["exp"]:
|
|
457
|
+
S["expired"] = True
|
|
458
|
+
S["leave"] = now + 600
|
|
459
|
+
for c in list(CONNS):
|
|
460
|
+
shut(c)
|
|
461
|
+
if S["expired"] and now >= S["leave"]:
|
|
462
|
+
os._exit(0)
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
async def main():
|
|
466
|
+
for p in PORTS:
|
|
467
|
+
try:
|
|
468
|
+
server = await asyncio.start_server(conn, "0.0.0.0", p, limit=MAX_HEAD)
|
|
469
|
+
except OSError:
|
|
470
|
+
continue
|
|
471
|
+
port = server.sockets[0].getsockname()[1]
|
|
472
|
+
S["cookie"] = "sr_gate_%d" % port
|
|
473
|
+
sys.stdout.write("SRGATE port=%d\n" % port)
|
|
474
|
+
sys.stdout.flush()
|
|
475
|
+
await watch()
|
|
476
|
+
sys.stdout.write("SRGATE fail\n")
|
|
477
|
+
sys.stdout.flush()
|
|
478
|
+
sys.exit(3)
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
asyncio.new_event_loop().run_until_complete(main())
|
|
482
|
+
`;
|
package/dist/index.d.ts
CHANGED
|
@@ -14,6 +14,11 @@ export { CATALOG, hourlyCost, unfit, info, billingRules, billedUsd, type Provide
|
|
|
14
14
|
export { createApp, HttpError, ERROR_STATUS, ORPHAN_GRACE_MS, type ServerHooks } from "./server.js";
|
|
15
15
|
export { Client, ClientError, RemoteSandbox, RemoteWorkspace, type CreateResponse, type WorkspaceInfo, type WorkspaceOptions, type WorkspaceWake } from "./client.js";
|
|
16
16
|
export { findSaved, folderStore, keepSaved, recoverSandbox, restoreFiles, saveFiles, DEFAULT_SAVE_EVERY_S, DEFAULT_SAVE_MAX_BYTES, type Keeper, type KeepOptions, type RecoverOptions, type RestoreOptions, type RestoreResult, type Saved, type SaveOptions, type SaveStore, } from "./save.js";
|
|
17
|
+
export { provideModule } from "./util.js";
|
|
18
|
+
export { attachCommand, spawnCommand, type AttachOptions, type SpawnBox, type Spawned, type SpawnOptions } from "./spawn.js";
|
|
19
|
+
export { attachTerminal, openTerminal, type Terminal, type TerminalAttachOptions, type TerminalBox, type TerminalOptions } from "./terminal.js";
|
|
20
|
+
export { previewLink, revokeGates, expireGates, DEFAULT_PREVIEW_SECONDS, MAX_PREVIEW_SECONDS, type GateRuntime, type PreviewBox, type PreviewLink, type PreviewOptions } from "./preview.js";
|
|
21
|
+
export { lingerSandbox, resumeSandbox, suspendSandbox, SELF_END, type EnforcedBy, type Lingering, type LingerOptions, type PausedSandbox, type Resumed, type ResumeOptions, type SavedSandbox, type Suspended, type SuspendOptions, } from "./lifecycle.js";
|
|
17
22
|
export { copyFiles, moveSandbox, DEFAULT_COPY_MAX_BYTES, type CopyOptions, type CopyResult, type FileBox, type MoveOptions, type Mover } from "./move.js";
|
|
18
23
|
export { RoutedComputer, createComputer, splitComputerRequest, DEFAULT_COMPUTER_TIMEOUT_S, DEFAULT_COMPUTER_DEADLINE_S, type ComputerRoute, planComputer, computerCatalog, computerHourly, COMPUTER_ENTRIES, type ComputerCatalogEntry, type ComputerCandidate, type ComputerProviderId, type ActionResult, type ComputerAction, type ComputerActionName, type ComputerInfo, type ComputerOs, type ComputerProvider, type ComputerSpec, type ProviderComputer, } from "./computers.js";
|
|
19
24
|
export { bench, benchMarkdown, type BenchRow } from "./bench.js";
|
package/dist/index.js
CHANGED
|
@@ -14,6 +14,11 @@ export { CATALOG, hourlyCost, unfit, info, billingRules, billedUsd } from "./cat
|
|
|
14
14
|
export { createApp, HttpError, ERROR_STATUS, ORPHAN_GRACE_MS } from "./server.js";
|
|
15
15
|
export { Client, ClientError, RemoteSandbox, RemoteWorkspace } from "./client.js";
|
|
16
16
|
export { findSaved, folderStore, keepSaved, recoverSandbox, restoreFiles, saveFiles, DEFAULT_SAVE_EVERY_S, DEFAULT_SAVE_MAX_BYTES, } from "./save.js";
|
|
17
|
+
export { provideModule } from "./util.js";
|
|
18
|
+
export { attachCommand, spawnCommand } from "./spawn.js";
|
|
19
|
+
export { attachTerminal, openTerminal } from "./terminal.js";
|
|
20
|
+
export { previewLink, revokeGates, expireGates, DEFAULT_PREVIEW_SECONDS, MAX_PREVIEW_SECONDS } from "./preview.js";
|
|
21
|
+
export { lingerSandbox, resumeSandbox, suspendSandbox, SELF_END, } from "./lifecycle.js";
|
|
17
22
|
export { copyFiles, moveSandbox, DEFAULT_COPY_MAX_BYTES } from "./move.js";
|
|
18
23
|
export { RoutedComputer, createComputer, splitComputerRequest, DEFAULT_COMPUTER_TIMEOUT_S, DEFAULT_COMPUTER_DEADLINE_S, planComputer, computerCatalog, computerHourly, COMPUTER_ENTRIES, } from "./computers.js";
|
|
19
24
|
export { bench, benchMarkdown } from "./bench.js";
|
package/dist/leaderboard.d.ts
CHANGED
|
@@ -121,6 +121,18 @@ export interface BurstReport {
|
|
|
121
121
|
rows: import("./burst.js").BurstRow[];
|
|
122
122
|
}
|
|
123
123
|
export declare function loadBursts(dir: string): BurstReport[];
|
|
124
|
+
/**
|
|
125
|
+
* A burst that an account limit (a quota, plan cap or rate limit, the report's `limited` count) stopped short of
|
|
126
|
+
* its size never tested the provider at that size. Such a row is not a result: it is left out of rankings and of
|
|
127
|
+
* the published numbers, and listed only as "not tested at this size".
|
|
128
|
+
*/
|
|
129
|
+
export declare function cappedByLimit(r: {
|
|
130
|
+
n: number;
|
|
131
|
+
ok: number;
|
|
132
|
+
limited?: number;
|
|
133
|
+
}): boolean;
|
|
134
|
+
/** A table that compares fewer providers than this is not a ranking, and is not published as one. */
|
|
135
|
+
export declare const MIN_RANKED = 3;
|
|
124
136
|
/**
|
|
125
137
|
* Each provider's latest burst of each kind (plain, or with a job), newest location wins, for the website:
|
|
126
138
|
* how many started, time to interactive at p50/p95/p99, and what the burst cost. Most started first, then
|
package/dist/leaderboard.js
CHANGED
|
@@ -353,6 +353,16 @@ export function loadBursts(dir) {
|
|
|
353
353
|
}
|
|
354
354
|
return out;
|
|
355
355
|
}
|
|
356
|
+
/**
|
|
357
|
+
* A burst that an account limit (a quota, plan cap or rate limit, the report's `limited` count) stopped short of
|
|
358
|
+
* its size never tested the provider at that size. Such a row is not a result: it is left out of rankings and of
|
|
359
|
+
* the published numbers, and listed only as "not tested at this size".
|
|
360
|
+
*/
|
|
361
|
+
export function cappedByLimit(r) {
|
|
362
|
+
return r.ok < r.n && (r.limited ?? 0) > 0;
|
|
363
|
+
}
|
|
364
|
+
/** A table that compares fewer providers than this is not a ranking, and is not published as one. */
|
|
365
|
+
export const MIN_RANKED = 3;
|
|
356
366
|
/**
|
|
357
367
|
* Each provider's latest burst of each kind (plain, or with a job), newest location wins, for the website:
|
|
358
368
|
* how many started, time to interactive at p50/p95/p99, and what the burst cost. Most started first, then
|