@ai-ecoverse/slicc-agent 7.15.0 → 7.16.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 +10 -2
- package/dist/approvals/sudo.js +4 -0
- package/dist/approvals/sudo.js.map +2 -2
- package/dist/kernel/agent-users.js +7 -1
- package/dist/kernel/agent-users.js.map +3 -3
- package/dist/main.js +21 -14
- package/dist/main.js.map +2 -2
- package/dist/scoops/cli.js +20 -0
- package/dist/scoops/cli.js.map +2 -2
- package/dist/scoops/index.js +1 -0
- package/dist/scoops/index.js.map +2 -2
- package/dist/spectrum/index.js +1 -1
- package/dist/spectrum/index.js.map +2 -2
- package/dist/spectrum/sprinkle-port.js +5 -2
- package/dist/spectrum/sprinkle-port.js.map +2 -2
- package/dist/sprinkles/bridge.js +89 -0
- package/dist/sprinkles/bridge.js.map +7 -0
- package/dist/sprinkles/cgi-run.js +342 -0
- package/dist/sprinkles/cgi-run.js.map +7 -0
- package/dist/sprinkles/cgi.js +213 -0
- package/dist/sprinkles/cgi.js.map +7 -0
- package/dist/sprinkles/index.js +28 -9
- package/dist/sprinkles/index.js.map +3 -3
- package/dist/sprinkles/sprinkles.js +1 -1
- package/dist/sprinkles/sprinkles.js.map +1 -1
- package/dist/types/approvals/sudo.d.ts +1 -0
- package/dist/types/kernel/client.d.ts +3 -0
- package/dist/types/scoops/cli.d.ts +2 -0
- package/dist/types/scoops/index.d.ts +1 -0
- package/dist/types/spectrum/sprinkle-port.d.ts +1 -1
- package/dist/types/sprinkles/bridge.d.ts +30 -0
- package/dist/types/sprinkles/cgi-run.d.ts +59 -0
- package/dist/types/sprinkles/cgi.d.ts +69 -0
- package/dist/types/sprinkles/index.d.ts +5 -1
- package/dist/types/sprinkles/sprinkles.d.ts +1 -1
- package/package.json +4 -3
- package/packages/vfs-root/skills/sprinkles/SKILL.md +22 -3
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
import { dirname } from "../kernel/paths.js";
|
|
2
|
+
import {
|
|
3
|
+
CGI_DIR,
|
|
4
|
+
CGI_LIMITS,
|
|
5
|
+
cgiEnv,
|
|
6
|
+
inside,
|
|
7
|
+
methodOf,
|
|
8
|
+
openTo,
|
|
9
|
+
parseHead,
|
|
10
|
+
REASONS,
|
|
11
|
+
scriptOf,
|
|
12
|
+
shebang,
|
|
13
|
+
tagOf,
|
|
14
|
+
toBase64
|
|
15
|
+
} from "./cgi.js";
|
|
16
|
+
const missing = (reason) => ({ status: 404, reason });
|
|
17
|
+
async function real(fs, path) {
|
|
18
|
+
return fs.realpath(path).catch(() => void 0);
|
|
19
|
+
}
|
|
20
|
+
async function locate(fs, folder, script, uid) {
|
|
21
|
+
const root = await real(fs, folder);
|
|
22
|
+
if (!root) return missing(`${folder} is gone`);
|
|
23
|
+
const bin = await real(fs, `${folder}/${CGI_DIR}`);
|
|
24
|
+
if (!bin || !inside(bin, root)) return missing(`${folder} has no ${CGI_DIR}/`);
|
|
25
|
+
const path = await real(fs, `${folder}/${CGI_DIR}/${script}`);
|
|
26
|
+
if (!path || !inside(path, root)) return missing(`${CGI_DIR}/${script} isn't there`);
|
|
27
|
+
const stat = await fs.stat(path).catch(() => void 0);
|
|
28
|
+
if (!stat?.isFile) return missing(`${CGI_DIR}/${script} is no file`);
|
|
29
|
+
for (const each of /* @__PURE__ */ new Set([root, bin, dirname(path), path])) {
|
|
30
|
+
const why = openTo(await fs.stat(each), uid);
|
|
31
|
+
if (why) return { status: 403, reason: `${each} is refused: ${why}` };
|
|
32
|
+
}
|
|
33
|
+
return { path };
|
|
34
|
+
}
|
|
35
|
+
async function uidOf(fs, user) {
|
|
36
|
+
if (user === "root") return 0;
|
|
37
|
+
const passwd = await fs.readText("/etc/passwd").catch(() => "");
|
|
38
|
+
const line = passwd.split("\n").find((entry) => entry.startsWith(`${user}:`));
|
|
39
|
+
const uid = Number(line?.split(":")[2] ?? Number.NaN);
|
|
40
|
+
if (!Number.isInteger(uid)) throw new Error(`there is no kernel user ${user}`);
|
|
41
|
+
return uid;
|
|
42
|
+
}
|
|
43
|
+
async function launch(client, path, options) {
|
|
44
|
+
try {
|
|
45
|
+
return await client.spawn([path], options);
|
|
46
|
+
} catch (error) {
|
|
47
|
+
if (error.code !== "EACCES") throw error;
|
|
48
|
+
const line = shebang(await client.fs.readFile(path));
|
|
49
|
+
if (!line) throw new Error(`${path} can't run: it has no #! line`);
|
|
50
|
+
return client.spawn([...line, path], options);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
function joined(parts) {
|
|
54
|
+
const out = new Uint8Array(parts.reduce((sum, part) => sum + part.length, 0));
|
|
55
|
+
let at = 0;
|
|
56
|
+
for (const part of parts) {
|
|
57
|
+
out.set(part, at);
|
|
58
|
+
at += part.length;
|
|
59
|
+
}
|
|
60
|
+
return out;
|
|
61
|
+
}
|
|
62
|
+
function cgiReply(status, text, more = []) {
|
|
63
|
+
return {
|
|
64
|
+
status,
|
|
65
|
+
statusText: REASONS[status] ?? "",
|
|
66
|
+
headers: [["Content-Type", "text/plain; charset=utf-8"], ...more],
|
|
67
|
+
body: toBase64(new TextEncoder().encode(text ? `${text}
|
|
68
|
+
` : "")),
|
|
69
|
+
done: true,
|
|
70
|
+
stream: null
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
function plain(status) {
|
|
74
|
+
return { status, statusText: REASONS[status] ?? "", headers: [["Content-Type", "text/plain"]] };
|
|
75
|
+
}
|
|
76
|
+
async function appendLog(fs, path, text, max) {
|
|
77
|
+
const old = await fs.readFile(path).catch(() => new Uint8Array());
|
|
78
|
+
let all = joined([old, new TextEncoder().encode(text)]);
|
|
79
|
+
if (all.length > max) {
|
|
80
|
+
const cut = all.indexOf(10, all.length - Math.floor(max / 2));
|
|
81
|
+
all = all.subarray(cut < 0 ? all.length - Math.floor(max / 2) : cut + 1);
|
|
82
|
+
}
|
|
83
|
+
await fs.writeFile(path, all);
|
|
84
|
+
}
|
|
85
|
+
function lines(at, script, text) {
|
|
86
|
+
const stamp = at.toISOString();
|
|
87
|
+
return text.split("\n").filter((line) => line.trim()).map((line) => `[${stamp}] ${script}: ${line}
|
|
88
|
+
`).join("");
|
|
89
|
+
}
|
|
90
|
+
const encode = (text) => new TextEncoder().encode(text);
|
|
91
|
+
class CgiRun {
|
|
92
|
+
sprinkle;
|
|
93
|
+
answered;
|
|
94
|
+
process;
|
|
95
|
+
ended = false;
|
|
96
|
+
why;
|
|
97
|
+
#limits;
|
|
98
|
+
#publish;
|
|
99
|
+
#settle;
|
|
100
|
+
#early = [];
|
|
101
|
+
#queue = [];
|
|
102
|
+
#total = 0;
|
|
103
|
+
#errors = [];
|
|
104
|
+
#errorBytes = 0;
|
|
105
|
+
#head;
|
|
106
|
+
#waiting = [];
|
|
107
|
+
#bodiless;
|
|
108
|
+
constructor(sprinkle, limits, publish, bodiless = false) {
|
|
109
|
+
this.sprinkle = sprinkle;
|
|
110
|
+
this.#bodiless = bodiless;
|
|
111
|
+
this.#limits = limits;
|
|
112
|
+
this.#publish = publish;
|
|
113
|
+
const { promise, resolve } = Promise.withResolvers();
|
|
114
|
+
this.answered = promise;
|
|
115
|
+
this.#settle = resolve;
|
|
116
|
+
}
|
|
117
|
+
stop(why) {
|
|
118
|
+
this.why ??= why;
|
|
119
|
+
void this.process?.signal("SIGKILL");
|
|
120
|
+
}
|
|
121
|
+
fail(message) {
|
|
122
|
+
this.#settle(cgiReply(500, message));
|
|
123
|
+
}
|
|
124
|
+
out = (bytes) => {
|
|
125
|
+
if (this.ended || this.why) return;
|
|
126
|
+
this.#total += bytes.length;
|
|
127
|
+
if (this.#total > this.#limits.output) {
|
|
128
|
+
this.stop(`its output passed ${this.#limits.output} bytes`);
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
if (this.#head) {
|
|
132
|
+
this.#queue.push(bytes);
|
|
133
|
+
this.#wake();
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
this.#early.push(bytes);
|
|
137
|
+
this.#headed(false);
|
|
138
|
+
};
|
|
139
|
+
err = (bytes) => {
|
|
140
|
+
const room = this.#limits.stderr - this.#errorBytes;
|
|
141
|
+
if (room <= 0) return;
|
|
142
|
+
const kept = bytes.subarray(0, room);
|
|
143
|
+
this.#errors.push(kept);
|
|
144
|
+
this.#errorBytes += kept.length;
|
|
145
|
+
};
|
|
146
|
+
end(code) {
|
|
147
|
+
this.ended = true;
|
|
148
|
+
const stderr = new TextDecoder().decode(joined(this.#errors));
|
|
149
|
+
if (!this.#head && this.#total === 0) this.#silent(code, stderr);
|
|
150
|
+
else this.#headed(true);
|
|
151
|
+
this.#wake();
|
|
152
|
+
const timeout = `timed out after ${this.#limits.timeoutMs / 1e3} s`;
|
|
153
|
+
return [
|
|
154
|
+
stderr,
|
|
155
|
+
this.why === "timeout" ? timeout : this.why,
|
|
156
|
+
code === void 0 || code === 0 ? void 0 : `exited ${code}`
|
|
157
|
+
].filter(Boolean).join("\n");
|
|
158
|
+
}
|
|
159
|
+
drain() {
|
|
160
|
+
const body = this.#bodiless ? "" : toBase64(joined(this.#queue));
|
|
161
|
+
this.#queue = [];
|
|
162
|
+
return body;
|
|
163
|
+
}
|
|
164
|
+
get pending() {
|
|
165
|
+
return this.#queue.length > 0;
|
|
166
|
+
}
|
|
167
|
+
wait(ms, later) {
|
|
168
|
+
if (this.pending || this.ended) return Promise.resolve();
|
|
169
|
+
return new Promise((resolve) => {
|
|
170
|
+
const cancel = later(ms, resolve);
|
|
171
|
+
this.#waiting.push(() => {
|
|
172
|
+
cancel();
|
|
173
|
+
resolve();
|
|
174
|
+
});
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
#wake() {
|
|
178
|
+
for (const resolve of this.#waiting.splice(0)) resolve();
|
|
179
|
+
}
|
|
180
|
+
#silent(code, stderr) {
|
|
181
|
+
const status = this.why === "timeout" ? 504 : code === void 0 ? 502 : code ? 500 : 200;
|
|
182
|
+
this.#head = plain(status);
|
|
183
|
+
const said = stderr || (this.why === "timeout" ? "timed out\n" : `exit ${code ?? "?"}
|
|
184
|
+
`);
|
|
185
|
+
if (status !== 200) this.#queue.push(encode(said));
|
|
186
|
+
this.#answer();
|
|
187
|
+
}
|
|
188
|
+
#headed(ended) {
|
|
189
|
+
if (this.#head) return;
|
|
190
|
+
const bytes = joined(this.#early);
|
|
191
|
+
const parsed = parseHead(bytes, ended);
|
|
192
|
+
if (parsed.kind === "more") return;
|
|
193
|
+
this.#early = [];
|
|
194
|
+
if (parsed.kind === "head") {
|
|
195
|
+
this.#head = parsed.head;
|
|
196
|
+
if (parsed.body.length) this.#queue.push(parsed.body);
|
|
197
|
+
} else if (parsed.kind === "body") {
|
|
198
|
+
this.#head = plain(200);
|
|
199
|
+
this.#queue.push(bytes);
|
|
200
|
+
} else {
|
|
201
|
+
this.#head = plain(502);
|
|
202
|
+
this.#queue.push(encode(`${parsed.reason}
|
|
203
|
+
`));
|
|
204
|
+
this.stop(parsed.reason);
|
|
205
|
+
}
|
|
206
|
+
this.#answer();
|
|
207
|
+
}
|
|
208
|
+
#answer() {
|
|
209
|
+
const head = this.#head;
|
|
210
|
+
const done = this.ended && !this.pending;
|
|
211
|
+
const stream = done ? null : this.#publish(this);
|
|
212
|
+
this.#settle({ ...head, body: this.drain(), done, stream });
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
function cgiRunner(limits = CGI_LIMITS, now = () => /* @__PURE__ */ new Date()) {
|
|
216
|
+
const running = /* @__PURE__ */ new Map();
|
|
217
|
+
const streams = /* @__PURE__ */ new Map();
|
|
218
|
+
const logs = /* @__PURE__ */ new Map();
|
|
219
|
+
const timers = /* @__PURE__ */ new Set();
|
|
220
|
+
const later = (ms, run) => {
|
|
221
|
+
const timer = setTimeout(() => {
|
|
222
|
+
timers.delete(timer);
|
|
223
|
+
run();
|
|
224
|
+
}, ms);
|
|
225
|
+
timers.add(timer);
|
|
226
|
+
return () => {
|
|
227
|
+
clearTimeout(timer);
|
|
228
|
+
timers.delete(timer);
|
|
229
|
+
};
|
|
230
|
+
};
|
|
231
|
+
const count = (id, by) => running.set(id, (running.get(id) ?? 0) + by);
|
|
232
|
+
const log = (fs, folder, script, text) => {
|
|
233
|
+
const added = lines(now(), script, text);
|
|
234
|
+
if (!added) return;
|
|
235
|
+
const path = `${folder}/error.log`;
|
|
236
|
+
const next = (logs.get(path) ?? Promise.resolve()).then(() => appendLog(fs, path, added, limits.log)).catch(() => void 0);
|
|
237
|
+
logs.set(path, next);
|
|
238
|
+
};
|
|
239
|
+
const publish = (run) => {
|
|
240
|
+
const id = crypto.randomUUID();
|
|
241
|
+
streams.set(id, run);
|
|
242
|
+
return id;
|
|
243
|
+
};
|
|
244
|
+
const execute = (site, kernel, request, path) => {
|
|
245
|
+
const { script, pathInfo } = scriptOf(request.path);
|
|
246
|
+
const run = new CgiRun(site.id, limits, publish, request.method === "HEAD");
|
|
247
|
+
const fs = kernel.client.fs;
|
|
248
|
+
const env = cgiEnv({
|
|
249
|
+
request,
|
|
250
|
+
script,
|
|
251
|
+
pathInfo,
|
|
252
|
+
...site,
|
|
253
|
+
sprinkle: site.id,
|
|
254
|
+
user: kernel.user
|
|
255
|
+
});
|
|
256
|
+
count(site.id, 1);
|
|
257
|
+
const ended = (code) => {
|
|
258
|
+
count(site.id, -1);
|
|
259
|
+
log(fs, site.folder, script, run.end(code));
|
|
260
|
+
later(limits.keepMs, () => {
|
|
261
|
+
for (const [id, kept] of streams) if (kept === run) streams.delete(id);
|
|
262
|
+
});
|
|
263
|
+
};
|
|
264
|
+
const started = (process) => {
|
|
265
|
+
run.process = process;
|
|
266
|
+
if (run.why) void process.signal("SIGKILL");
|
|
267
|
+
const cancel = later(limits.timeoutMs, () => run.stop("timeout"));
|
|
268
|
+
process.exited.then(
|
|
269
|
+
(code) => ended(code),
|
|
270
|
+
() => ended(void 0)
|
|
271
|
+
).finally(cancel);
|
|
272
|
+
};
|
|
273
|
+
launch(kernel.client, path, {
|
|
274
|
+
cwd: site.folder,
|
|
275
|
+
env,
|
|
276
|
+
tag: tagOf(site.id),
|
|
277
|
+
...request.body ? { stdin: request.body } : {},
|
|
278
|
+
onStdout: run.out,
|
|
279
|
+
onStderr: run.err
|
|
280
|
+
}).then(started, (error) => {
|
|
281
|
+
count(site.id, -1);
|
|
282
|
+
log(fs, site.folder, script, error.message);
|
|
283
|
+
run.fail(error.message);
|
|
284
|
+
});
|
|
285
|
+
return run.answered;
|
|
286
|
+
};
|
|
287
|
+
const refused = async (site, kernel, request) => {
|
|
288
|
+
const parts = scriptOf(request.path);
|
|
289
|
+
if (!parts) return cgiReply(404, `there is no ${CGI_DIR}/${request.path}`);
|
|
290
|
+
if (request.body && request.body.length > limits.input)
|
|
291
|
+
return cgiReply(413, `a ${CGI_DIR} request body is at most ${limits.input} bytes`);
|
|
292
|
+
if ((running.get(site.id) ?? 0) >= limits.parallel)
|
|
293
|
+
return cgiReply(503, `${site.id} runs ${limits.parallel} scripts already`, [
|
|
294
|
+
["Retry-After", "1"]
|
|
295
|
+
]);
|
|
296
|
+
const fs = kernel.client.fs;
|
|
297
|
+
const found = await uidOf(fs, kernel.user).then(
|
|
298
|
+
(uid) => locate(fs, site.folder, parts.script, uid),
|
|
299
|
+
(error) => ({ status: 403, reason: error.message })
|
|
300
|
+
);
|
|
301
|
+
if (!("status" in found)) return found.path;
|
|
302
|
+
if (found.status === 403) log(fs, site.folder, parts.script, found.reason);
|
|
303
|
+
return cgiReply(found.status, found.reason);
|
|
304
|
+
};
|
|
305
|
+
return {
|
|
306
|
+
async start(site, kernel, request) {
|
|
307
|
+
const method = methodOf(request.method);
|
|
308
|
+
if (!method) return cgiReply(400, "the method is no HTTP token");
|
|
309
|
+
const path = await refused(site, kernel, request);
|
|
310
|
+
return typeof path === "string" ? execute(site, kernel, { ...request, method }, path) : path;
|
|
311
|
+
},
|
|
312
|
+
async read(stream, sprinkle) {
|
|
313
|
+
const run = streams.get(stream);
|
|
314
|
+
if (run?.sprinkle !== sprinkle) throw new Error(`there is no ${CGI_DIR} stream ${stream}`);
|
|
315
|
+
await run.wait(limits.pollMs, later);
|
|
316
|
+
const body = run.drain();
|
|
317
|
+
if (run.ended) streams.delete(stream);
|
|
318
|
+
return { body, done: run.ended };
|
|
319
|
+
},
|
|
320
|
+
close(stream, sprinkle) {
|
|
321
|
+
const run = streams.get(stream);
|
|
322
|
+
if (run?.sprinkle !== sprinkle) return;
|
|
323
|
+
streams.delete(stream);
|
|
324
|
+
run.stop("the frame stopped reading its output");
|
|
325
|
+
},
|
|
326
|
+
stop() {
|
|
327
|
+
for (const timer of timers) clearTimeout(timer);
|
|
328
|
+
timers.clear();
|
|
329
|
+
for (const run of new Set(streams.values())) run.stop("the worker closed");
|
|
330
|
+
streams.clear();
|
|
331
|
+
}
|
|
332
|
+
};
|
|
333
|
+
}
|
|
334
|
+
export {
|
|
335
|
+
CgiRun,
|
|
336
|
+
appendLog,
|
|
337
|
+
cgiReply,
|
|
338
|
+
cgiRunner,
|
|
339
|
+
locate,
|
|
340
|
+
uidOf
|
|
341
|
+
};
|
|
342
|
+
//# sourceMappingURL=cgi-run.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/sprinkles/cgi-run.ts"],
|
|
4
|
+
"sourcesContent": ["import type { KernelClient, KernelFs, KernelProcess, SpawnOptions } from '../kernel/client.ts';\nimport { dirname } from '../kernel/paths.ts';\nimport {\n CGI_DIR,\n CGI_LIMITS,\n type CgiHead,\n type CgiHeaders,\n type CgiRequest,\n cgiEnv,\n inside,\n methodOf,\n openTo,\n parseHead,\n REASONS,\n scriptOf,\n shebang,\n tagOf,\n toBase64,\n} from './cgi.ts';\n\nexport interface CgiKernel {\n client: KernelClient;\n user: string;\n}\n\nexport interface CgiSite {\n id: string;\n folder: string;\n owner: string;\n}\n\nexport interface CgiReply {\n status: number;\n statusText: string;\n headers: CgiHeaders;\n body: string;\n done: boolean;\n stream: string | null;\n}\n\nexport interface CgiChunk {\n body: string;\n done: boolean;\n}\n\nexport interface CgiRunner {\n start(site: CgiSite, kernel: CgiKernel, request: CgiRequest): Promise<CgiReply>;\n read(stream: string, sprinkle: string): Promise<CgiChunk>;\n close(stream: string, sprinkle: string): void;\n stop(): void;\n}\n\nexport type CgiLimits = typeof CGI_LIMITS;\n\ntype Found = { path: string } | { status: 403 | 404; reason: string };\n\nconst missing = (reason: string): Found => ({ status: 404, reason });\n\nasync function real(fs: KernelFs, path: string): Promise<string | undefined> {\n return fs.realpath(path).catch(() => undefined);\n}\n\nexport async function locate(\n fs: KernelFs,\n folder: string,\n script: string,\n uid: number\n): Promise<Found> {\n const root = await real(fs, folder);\n if (!root) return missing(`${folder} is gone`);\n const bin = await real(fs, `${folder}/${CGI_DIR}`);\n if (!bin || !inside(bin, root)) return missing(`${folder} has no ${CGI_DIR}/`);\n const path = await real(fs, `${folder}/${CGI_DIR}/${script}`);\n if (!path || !inside(path, root)) return missing(`${CGI_DIR}/${script} isn't there`);\n const stat = await fs.stat(path).catch(() => undefined);\n if (!stat?.isFile) return missing(`${CGI_DIR}/${script} is no file`);\n for (const each of new Set([root, bin, dirname(path), path])) {\n const why = openTo(await fs.stat(each), uid);\n if (why) return { status: 403, reason: `${each} is refused: ${why}` };\n }\n return { path };\n}\n\nexport async function uidOf(fs: KernelFs, user: string): Promise<number> {\n if (user === 'root') return 0;\n const passwd = await fs.readText('/etc/passwd').catch(() => '');\n const line = passwd.split('\\n').find((entry) => entry.startsWith(`${user}:`));\n const uid = Number(line?.split(':')[2] ?? Number.NaN);\n if (!Number.isInteger(uid)) throw new Error(`there is no kernel user ${user}`);\n return uid;\n}\n\nasync function launch(\n client: KernelClient,\n path: string,\n options: SpawnOptions\n): Promise<KernelProcess> {\n try {\n return await client.spawn([path], options);\n } catch (error) {\n if ((error as { code?: unknown }).code !== 'EACCES') throw error;\n const line = shebang(await client.fs.readFile(path));\n if (!line) throw new Error(`${path} can't run: it has no #! line`);\n return client.spawn([...line, path], options);\n }\n}\n\nfunction joined(parts: readonly Uint8Array[]): Uint8Array {\n const out = new Uint8Array(parts.reduce((sum, part) => sum + part.length, 0));\n let at = 0;\n for (const part of parts) {\n out.set(part, at);\n at += part.length;\n }\n return out;\n}\n\nexport function cgiReply(status: number, text: string, more: CgiHeaders = []): CgiReply {\n return {\n status,\n statusText: REASONS[status] ?? '',\n headers: [['Content-Type', 'text/plain; charset=utf-8'], ...more],\n body: toBase64(new TextEncoder().encode(text ? `${text}\\n` : '')),\n done: true,\n stream: null,\n };\n}\n\nfunction plain(status: number): CgiHead {\n return { status, statusText: REASONS[status] ?? '', headers: [['Content-Type', 'text/plain']] };\n}\n\nexport async function appendLog(fs: KernelFs, path: string, text: string, max: number) {\n const old = await fs.readFile(path).catch(() => new Uint8Array());\n let all = joined([old, new TextEncoder().encode(text)]);\n if (all.length > max) {\n const cut = all.indexOf(10, all.length - Math.floor(max / 2));\n all = all.subarray(cut < 0 ? all.length - Math.floor(max / 2) : cut + 1);\n }\n await fs.writeFile(path, all);\n}\n\nfunction lines(at: Date, script: string, text: string): string {\n const stamp = at.toISOString();\n return text\n .split('\\n')\n .filter((line) => line.trim())\n .map((line) => `[${stamp}] ${script}: ${line}\\n`)\n .join('');\n}\n\nconst encode = (text: string) => new TextEncoder().encode(text);\n\nexport class CgiRun {\n readonly sprinkle: string;\n readonly answered: Promise<CgiReply>;\n process: KernelProcess | undefined;\n ended = false;\n why: string | undefined;\n readonly #limits: CgiLimits;\n readonly #publish: (run: CgiRun) => string;\n readonly #settle: (reply: CgiReply) => void;\n #early: Uint8Array[] = [];\n #queue: Uint8Array[] = [];\n #total = 0;\n #errors: Uint8Array[] = [];\n #errorBytes = 0;\n #head: CgiHead | undefined;\n #waiting: (() => void)[] = [];\n readonly #bodiless: boolean;\n\n constructor(\n sprinkle: string,\n limits: CgiLimits,\n publish: (run: CgiRun) => string,\n bodiless = false\n ) {\n this.sprinkle = sprinkle;\n this.#bodiless = bodiless;\n this.#limits = limits;\n this.#publish = publish;\n const { promise, resolve } = Promise.withResolvers<CgiReply>();\n this.answered = promise;\n this.#settle = resolve;\n }\n\n stop(why: string): void {\n this.why ??= why;\n void this.process?.signal('SIGKILL');\n }\n\n fail(message: string): void {\n this.#settle(cgiReply(500, message));\n }\n\n readonly out = (bytes: Uint8Array): void => {\n if (this.ended || this.why) return;\n this.#total += bytes.length;\n if (this.#total > this.#limits.output) {\n this.stop(`its output passed ${this.#limits.output} bytes`);\n return;\n }\n if (this.#head) {\n this.#queue.push(bytes);\n this.#wake();\n return;\n }\n this.#early.push(bytes);\n this.#headed(false);\n };\n\n readonly err = (bytes: Uint8Array): void => {\n const room = this.#limits.stderr - this.#errorBytes;\n if (room <= 0) return;\n const kept = bytes.subarray(0, room);\n this.#errors.push(kept);\n this.#errorBytes += kept.length;\n };\n\n end(code: number | undefined): string {\n this.ended = true;\n const stderr = new TextDecoder().decode(joined(this.#errors));\n if (!this.#head && this.#total === 0) this.#silent(code, stderr);\n else this.#headed(true);\n this.#wake();\n const timeout = `timed out after ${this.#limits.timeoutMs / 1000} s`;\n return [\n stderr,\n this.why === 'timeout' ? timeout : this.why,\n code === undefined || code === 0 ? undefined : `exited ${code}`,\n ]\n .filter(Boolean)\n .join('\\n');\n }\n\n drain(): string {\n const body = this.#bodiless ? '' : toBase64(joined(this.#queue));\n this.#queue = [];\n return body;\n }\n\n get pending(): boolean {\n return this.#queue.length > 0;\n }\n\n wait(ms: number, later: (ms: number, run: () => void) => () => void): Promise<void> {\n if (this.pending || this.ended) return Promise.resolve();\n return new Promise((resolve) => {\n const cancel = later(ms, resolve);\n this.#waiting.push(() => {\n cancel();\n resolve();\n });\n });\n }\n\n #wake(): void {\n for (const resolve of this.#waiting.splice(0)) resolve();\n }\n\n #silent(code: number | undefined, stderr: string): void {\n const status = this.why === 'timeout' ? 504 : code === undefined ? 502 : code ? 500 : 200;\n this.#head = plain(status);\n const said = stderr || (this.why === 'timeout' ? 'timed out\\n' : `exit ${code ?? '?'}\\n`);\n if (status !== 200) this.#queue.push(encode(said));\n this.#answer();\n }\n\n #headed(ended: boolean): void {\n if (this.#head) return;\n const bytes = joined(this.#early);\n const parsed = parseHead(bytes, ended);\n if (parsed.kind === 'more') return;\n this.#early = [];\n if (parsed.kind === 'head') {\n this.#head = parsed.head;\n if (parsed.body.length) this.#queue.push(parsed.body);\n } else if (parsed.kind === 'body') {\n this.#head = plain(200);\n this.#queue.push(bytes);\n } else {\n this.#head = plain(502);\n this.#queue.push(encode(`${parsed.reason}\\n`));\n this.stop(parsed.reason);\n }\n this.#answer();\n }\n\n #answer(): void {\n const head = this.#head as CgiHead;\n const done = this.ended && !this.pending;\n const stream = done ? null : this.#publish(this);\n this.#settle({ ...head, body: this.drain(), done, stream });\n }\n}\n\nexport function cgiRunner(\n limits: CgiLimits = CGI_LIMITS,\n now: () => Date = () => new Date()\n): CgiRunner {\n const running = new Map<string, number>();\n const streams = new Map<string, CgiRun>();\n const logs = new Map<string, Promise<void>>();\n const timers = new Set<ReturnType<typeof setTimeout>>();\n const later = (ms: number, run: () => void) => {\n const timer = setTimeout(() => {\n timers.delete(timer);\n run();\n }, ms);\n timers.add(timer);\n return () => {\n clearTimeout(timer);\n timers.delete(timer);\n };\n };\n const count = (id: string, by: number) => running.set(id, (running.get(id) ?? 0) + by);\n const log = (fs: KernelFs, folder: string, script: string, text: string) => {\n const added = lines(now(), script, text);\n if (!added) return;\n const path = `${folder}/error.log`;\n const next = (logs.get(path) ?? Promise.resolve())\n .then(() => appendLog(fs, path, added, limits.log))\n .catch(() => undefined);\n logs.set(path, next);\n };\n const publish = (run: CgiRun) => {\n const id = crypto.randomUUID();\n streams.set(id, run);\n return id;\n };\n const execute = (site: CgiSite, kernel: CgiKernel, request: CgiRequest, path: string) => {\n const { script, pathInfo } = scriptOf(request.path) as { script: string; pathInfo: string };\n const run = new CgiRun(site.id, limits, publish, request.method === 'HEAD');\n const fs = kernel.client.fs;\n const env = cgiEnv({\n request,\n script,\n pathInfo,\n ...site,\n sprinkle: site.id,\n user: kernel.user,\n });\n count(site.id, 1);\n const ended = (code: number | undefined) => {\n count(site.id, -1);\n log(fs, site.folder, script, run.end(code));\n later(limits.keepMs, () => {\n for (const [id, kept] of streams) if (kept === run) streams.delete(id);\n });\n };\n const started = (process: KernelProcess) => {\n run.process = process;\n if (run.why) void process.signal('SIGKILL');\n const cancel = later(limits.timeoutMs, () => run.stop('timeout'));\n process.exited\n .then(\n (code) => ended(code),\n () => ended(undefined)\n )\n .finally(cancel);\n };\n launch(kernel.client, path, {\n cwd: site.folder,\n env,\n tag: tagOf(site.id),\n ...(request.body ? { stdin: request.body } : {}),\n onStdout: run.out,\n onStderr: run.err,\n }).then(started, (error: Error) => {\n count(site.id, -1);\n log(fs, site.folder, script, error.message);\n run.fail(error.message);\n });\n return run.answered;\n };\n const refused = async (site: CgiSite, kernel: CgiKernel, request: CgiRequest) => {\n const parts = scriptOf(request.path);\n if (!parts) return cgiReply(404, `there is no ${CGI_DIR}/${request.path}`);\n if (request.body && request.body.length > limits.input)\n return cgiReply(413, `a ${CGI_DIR} request body is at most ${limits.input} bytes`);\n if ((running.get(site.id) ?? 0) >= limits.parallel)\n return cgiReply(503, `${site.id} runs ${limits.parallel} scripts already`, [\n ['Retry-After', '1'],\n ]);\n const fs = kernel.client.fs;\n const found = await uidOf(fs, kernel.user).then(\n (uid) => locate(fs, site.folder, parts.script, uid),\n (error: Error): Found => ({ status: 403, reason: error.message })\n );\n if (!('status' in found)) return found.path;\n if (found.status === 403) log(fs, site.folder, parts.script, found.reason);\n return cgiReply(found.status, found.reason);\n };\n return {\n async start(site, kernel, request) {\n const method = methodOf(request.method);\n if (!method) return cgiReply(400, 'the method is no HTTP token');\n const path = await refused(site, kernel, request);\n return typeof path === 'string' ? execute(site, kernel, { ...request, method }, path) : path;\n },\n async read(stream, sprinkle) {\n const run = streams.get(stream);\n if (run?.sprinkle !== sprinkle) throw new Error(`there is no ${CGI_DIR} stream ${stream}`);\n await run.wait(limits.pollMs, later);\n const body = run.drain();\n if (run.ended) streams.delete(stream);\n return { body, done: run.ended };\n },\n close(stream, sprinkle) {\n const run = streams.get(stream);\n if (run?.sprinkle !== sprinkle) return;\n streams.delete(stream);\n run.stop('the frame stopped reading its output');\n },\n stop() {\n for (const timer of timers) clearTimeout(timer);\n timers.clear();\n for (const run of new Set(streams.values())) run.stop('the worker closed');\n streams.clear();\n },\n };\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,eAAe;AACxB;AAAA,EACE;AAAA,EACA;AAAA,EAIA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAsCP,MAAM,UAAU,CAAC,YAA2B,EAAE,QAAQ,KAAK,OAAO;AAElE,eAAe,KAAK,IAAc,MAA2C;AAC3E,SAAO,GAAG,SAAS,IAAI,EAAE,MAAM,MAAM,MAAS;AAChD;AAEA,eAAsB,OACpB,IACA,QACA,QACA,KACgB;AAChB,QAAM,OAAO,MAAM,KAAK,IAAI,MAAM;AAClC,MAAI,CAAC,KAAM,QAAO,QAAQ,GAAG,MAAM,UAAU;AAC7C,QAAM,MAAM,MAAM,KAAK,IAAI,GAAG,MAAM,IAAI,OAAO,EAAE;AACjD,MAAI,CAAC,OAAO,CAAC,OAAO,KAAK,IAAI,EAAG,QAAO,QAAQ,GAAG,MAAM,WAAW,OAAO,GAAG;AAC7E,QAAM,OAAO,MAAM,KAAK,IAAI,GAAG,MAAM,IAAI,OAAO,IAAI,MAAM,EAAE;AAC5D,MAAI,CAAC,QAAQ,CAAC,OAAO,MAAM,IAAI,EAAG,QAAO,QAAQ,GAAG,OAAO,IAAI,MAAM,cAAc;AACnF,QAAM,OAAO,MAAM,GAAG,KAAK,IAAI,EAAE,MAAM,MAAM,MAAS;AACtD,MAAI,CAAC,MAAM,OAAQ,QAAO,QAAQ,GAAG,OAAO,IAAI,MAAM,aAAa;AACnE,aAAW,QAAQ,oBAAI,IAAI,CAAC,MAAM,KAAK,QAAQ,IAAI,GAA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I,IAAI,QAAQ,OAAO,CAAC,EAAG,KAAI,KAAK,mBAAmB;AACzE,cAAQ,MAAM;AAAA,IAChB;AAAA,EACF;AACF;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
const CGI_DIR = "cgi-bin";
|
|
2
|
+
const CGI_TAG = "sprinkle:";
|
|
3
|
+
const CGI_LIMITS = {
|
|
4
|
+
input: 64 * 1024,
|
|
5
|
+
output: 4 * 1024 * 1024,
|
|
6
|
+
stderr: 64 * 1024,
|
|
7
|
+
head: 64 * 1024,
|
|
8
|
+
timeoutMs: 3e4,
|
|
9
|
+
parallel: 4,
|
|
10
|
+
pollMs: 2e4,
|
|
11
|
+
keepMs: 6e4,
|
|
12
|
+
log: 1024 * 1024
|
|
13
|
+
};
|
|
14
|
+
const TOKEN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
|
|
15
|
+
const PREFIX = /^[!#$%&'*+.^_`|~0-9A-Za-z-]*$/;
|
|
16
|
+
const HEADER = /^([!#$%&'*+.^_`|~0-9A-Za-z-]+):[ \t]*(.*?)[ \t]*$/;
|
|
17
|
+
const STATUS = /^([2-5][0-9][0-9])(?:[ \t]+(.*))?$/;
|
|
18
|
+
const HOP = /* @__PURE__ */ new Set([
|
|
19
|
+
"connection",
|
|
20
|
+
"keep-alive",
|
|
21
|
+
"proxy-connection",
|
|
22
|
+
"te",
|
|
23
|
+
"trailer",
|
|
24
|
+
"transfer-encoding",
|
|
25
|
+
"upgrade"
|
|
26
|
+
]);
|
|
27
|
+
const REASONS = {
|
|
28
|
+
200: "OK",
|
|
29
|
+
201: "Created",
|
|
30
|
+
204: "No Content",
|
|
31
|
+
302: "Found",
|
|
32
|
+
400: "Bad Request",
|
|
33
|
+
403: "Forbidden",
|
|
34
|
+
404: "Not Found",
|
|
35
|
+
405: "Method Not Allowed",
|
|
36
|
+
413: "Payload Too Large",
|
|
37
|
+
500: "Internal Server Error",
|
|
38
|
+
502: "Bad Gateway",
|
|
39
|
+
503: "Service Unavailable",
|
|
40
|
+
504: "Gateway Timeout"
|
|
41
|
+
};
|
|
42
|
+
function scriptOf(path) {
|
|
43
|
+
if (typeof path !== "string" || !path) return void 0;
|
|
44
|
+
const segments = [];
|
|
45
|
+
for (const raw of path.split("/")) {
|
|
46
|
+
let segment;
|
|
47
|
+
try {
|
|
48
|
+
segment = decodeURIComponent(raw);
|
|
49
|
+
} catch {
|
|
50
|
+
return void 0;
|
|
51
|
+
}
|
|
52
|
+
if (segment === "." || segment === ".." || /[/\\\0]/.test(segment)) return void 0;
|
|
53
|
+
segments.push(segment);
|
|
54
|
+
}
|
|
55
|
+
const [script, ...rest] = segments;
|
|
56
|
+
if (!script || script.startsWith(".")) return void 0;
|
|
57
|
+
return { script, pathInfo: rest.length ? `/${rest.join("/")}` : "" };
|
|
58
|
+
}
|
|
59
|
+
function methodOf(method) {
|
|
60
|
+
return typeof method === "string" && TOKEN.test(method) ? method.toUpperCase() : void 0;
|
|
61
|
+
}
|
|
62
|
+
const clean = (value) => value.replace(/[\r\n\0]/g, " ");
|
|
63
|
+
function requestHeaders(headers) {
|
|
64
|
+
const out = {};
|
|
65
|
+
for (const [name, value] of headers) {
|
|
66
|
+
if (!TOKEN.test(name)) continue;
|
|
67
|
+
const key = name.toLowerCase();
|
|
68
|
+
if (key === "content-type" || key === "content-length" || key === "proxy") continue;
|
|
69
|
+
const at = `HTTP_${key.toUpperCase().replace(/-/g, "_")}`;
|
|
70
|
+
out[at] = out[at] === void 0 ? clean(value) : `${out[at]}, ${clean(value)}`;
|
|
71
|
+
}
|
|
72
|
+
return out;
|
|
73
|
+
}
|
|
74
|
+
function cgiEnv(at) {
|
|
75
|
+
const { request, script, pathInfo, folder } = at;
|
|
76
|
+
const type = request.headers.find(([name]) => name.toLowerCase() === "content-type")?.[1];
|
|
77
|
+
return {
|
|
78
|
+
...requestHeaders(request.headers),
|
|
79
|
+
GATEWAY_INTERFACE: "CGI/1.1",
|
|
80
|
+
SERVER_PROTOCOL: "HTTP/1.1",
|
|
81
|
+
SERVER_SOFTWARE: "slicc-agent",
|
|
82
|
+
SERVER_NAME: "localhost",
|
|
83
|
+
SERVER_PORT: "80",
|
|
84
|
+
REMOTE_ADDR: "127.0.0.1",
|
|
85
|
+
REQUEST_METHOD: request.method,
|
|
86
|
+
QUERY_STRING: request.query,
|
|
87
|
+
SCRIPT_NAME: `/${CGI_DIR}/${script}`,
|
|
88
|
+
SCRIPT_FILENAME: `${folder}/${CGI_DIR}/${script}`,
|
|
89
|
+
DOCUMENT_ROOT: folder,
|
|
90
|
+
REQUEST_URI: `/${CGI_DIR}/${request.path}${request.query ? `?${request.query}` : ""}`,
|
|
91
|
+
PATH_INFO: pathInfo,
|
|
92
|
+
...pathInfo ? { PATH_TRANSLATED: `${folder}${pathInfo}` } : {},
|
|
93
|
+
...request.body ? { CONTENT_LENGTH: String(request.body.length) } : {},
|
|
94
|
+
...request.body && type !== void 0 ? { CONTENT_TYPE: clean(type) } : {},
|
|
95
|
+
REMOTE_USER: at.user,
|
|
96
|
+
SLICC_SPRINKLE: at.sprinkle,
|
|
97
|
+
SLICC_OWNER: at.owner,
|
|
98
|
+
...request.tab ? { SLICC_TAB: request.tab } : {}
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
function lineEnd(bytes, from) {
|
|
102
|
+
return bytes.indexOf(10, from);
|
|
103
|
+
}
|
|
104
|
+
function decoded(bytes, from, to) {
|
|
105
|
+
const end = to > from && bytes[to - 1] === 13 ? to - 1 : to;
|
|
106
|
+
return new TextDecoder().decode(bytes.subarray(from, end));
|
|
107
|
+
}
|
|
108
|
+
function headOf(lines) {
|
|
109
|
+
let status;
|
|
110
|
+
let statusText = "";
|
|
111
|
+
const headers = [];
|
|
112
|
+
for (const line of lines) {
|
|
113
|
+
const [, name, value] = HEADER.exec(line);
|
|
114
|
+
const key = name.toLowerCase();
|
|
115
|
+
if (key === "status") {
|
|
116
|
+
const found = STATUS.exec(value);
|
|
117
|
+
if (!found) return `bad Status header: ${value}`;
|
|
118
|
+
status = Number(found[1]);
|
|
119
|
+
statusText = found[2] ?? "";
|
|
120
|
+
} else if (!HOP.has(key)) headers.push([name, value]);
|
|
121
|
+
}
|
|
122
|
+
const location = headers.some(([name]) => name.toLowerCase() === "location");
|
|
123
|
+
const code = status ?? (location ? 302 : 200);
|
|
124
|
+
if (!location && !headers.some(([name]) => name.toLowerCase() === "content-type"))
|
|
125
|
+
headers.push(["Content-Type", "text/plain"]);
|
|
126
|
+
return { status: code, statusText: statusText || REASONS[code] || "", headers };
|
|
127
|
+
}
|
|
128
|
+
function parseHead(bytes, ended) {
|
|
129
|
+
const lines = [];
|
|
130
|
+
let at = 0;
|
|
131
|
+
for (; ; ) {
|
|
132
|
+
const end = lineEnd(bytes, at);
|
|
133
|
+
if (end < 0) break;
|
|
134
|
+
const line = decoded(bytes, at, end);
|
|
135
|
+
at = end + 1;
|
|
136
|
+
if (line === "") {
|
|
137
|
+
if (!lines.length) return { kind: "body" };
|
|
138
|
+
const head2 = headOf(lines);
|
|
139
|
+
return typeof head2 === "string" ? { kind: "bad", reason: head2 } : { kind: "head", head: head2, body: bytes.subarray(at) };
|
|
140
|
+
}
|
|
141
|
+
if (!HEADER.test(line)) return { kind: "body" };
|
|
142
|
+
lines.push(line);
|
|
143
|
+
}
|
|
144
|
+
const rest = decoded(bytes, at, bytes.length);
|
|
145
|
+
if (rest && !HEADER.test(rest) && (ended || !PREFIX.test(rest))) return { kind: "body" };
|
|
146
|
+
if (!ended) return bytes.length > CGI_LIMITS.head ? { kind: "body" } : { kind: "more" };
|
|
147
|
+
if (rest) lines.push(rest);
|
|
148
|
+
if (!lines.length) return { kind: "body" };
|
|
149
|
+
const head = headOf(lines);
|
|
150
|
+
return typeof head === "string" ? { kind: "bad", reason: head } : { kind: "head", head, body: new Uint8Array() };
|
|
151
|
+
}
|
|
152
|
+
function shebang(bytes) {
|
|
153
|
+
if (bytes[0] !== 35 || bytes[1] !== 33) return void 0;
|
|
154
|
+
const end = bytes.indexOf(10);
|
|
155
|
+
const line = decoded(bytes, 2, end < 0 ? Math.min(bytes.length, 256) : end).trim();
|
|
156
|
+
const space = line.search(/[ \t]/);
|
|
157
|
+
if (!line) return void 0;
|
|
158
|
+
if (space < 0) return [line];
|
|
159
|
+
const arg = line.slice(space).trim();
|
|
160
|
+
return arg ? [line.slice(0, space), arg] : [line.slice(0, space)];
|
|
161
|
+
}
|
|
162
|
+
function openTo(stat, uid) {
|
|
163
|
+
if (stat.mode !== void 0 && (stat.mode & 18) !== 0)
|
|
164
|
+
return `its group or others can write it (mode ${(stat.mode & 511).toString(8)})`;
|
|
165
|
+
if (stat.uid !== void 0 && stat.uid !== 0 && stat.uid !== uid)
|
|
166
|
+
return `uid ${stat.uid} owns it, not the sprinkle's owner`;
|
|
167
|
+
return void 0;
|
|
168
|
+
}
|
|
169
|
+
function inside(path, root) {
|
|
170
|
+
return path.startsWith(`${root}/`);
|
|
171
|
+
}
|
|
172
|
+
function tagOf(id) {
|
|
173
|
+
return `${CGI_TAG}${id}`;
|
|
174
|
+
}
|
|
175
|
+
function sprinklesOf(tags) {
|
|
176
|
+
return [
|
|
177
|
+
...new Set(
|
|
178
|
+
tags.filter((tag) => tag.startsWith(CGI_TAG)).map((tag) => tag.slice(CGI_TAG.length))
|
|
179
|
+
)
|
|
180
|
+
];
|
|
181
|
+
}
|
|
182
|
+
function toBase64(bytes) {
|
|
183
|
+
let out = "";
|
|
184
|
+
for (let at = 0; at < bytes.length; at += 32768)
|
|
185
|
+
out += String.fromCharCode(...bytes.subarray(at, at + 32768));
|
|
186
|
+
return btoa(out);
|
|
187
|
+
}
|
|
188
|
+
function fromBase64(text) {
|
|
189
|
+
const raw = atob(text);
|
|
190
|
+
const out = new Uint8Array(raw.length);
|
|
191
|
+
for (let at = 0; at < raw.length; at++) out[at] = raw.charCodeAt(at);
|
|
192
|
+
return out;
|
|
193
|
+
}
|
|
194
|
+
export {
|
|
195
|
+
CGI_DIR,
|
|
196
|
+
CGI_LIMITS,
|
|
197
|
+
CGI_TAG,
|
|
198
|
+
REASONS,
|
|
199
|
+
cgiEnv,
|
|
200
|
+
fromBase64,
|
|
201
|
+
headOf,
|
|
202
|
+
inside,
|
|
203
|
+
methodOf,
|
|
204
|
+
openTo,
|
|
205
|
+
parseHead,
|
|
206
|
+
requestHeaders,
|
|
207
|
+
scriptOf,
|
|
208
|
+
shebang,
|
|
209
|
+
sprinklesOf,
|
|
210
|
+
tagOf,
|
|
211
|
+
toBase64
|
|
212
|
+
};
|
|
213
|
+
//# sourceMappingURL=cgi.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/sprinkles/cgi.ts"],
|
|
4
|
+
"sourcesContent": ["export const CGI_DIR = 'cgi-bin';\nexport const CGI_TAG = 'sprinkle:';\nexport const CGI_LIMITS = {\n input: 64 * 1024,\n output: 4 * 1024 * 1024,\n stderr: 64 * 1024,\n head: 64 * 1024,\n timeoutMs: 30_000,\n parallel: 4,\n pollMs: 20_000,\n keepMs: 60_000,\n log: 1024 * 1024,\n};\n\nexport type CgiHeaders = [string, string][];\n\nexport interface CgiRequest {\n method: string;\n path: string;\n query: string;\n headers: CgiHeaders;\n body: Uint8Array | null;\n tab: string | null;\n}\n\nexport interface CgiHead {\n status: number;\n statusText: string;\n headers: CgiHeaders;\n}\n\nexport type CgiParsed =\n | { kind: 'head'; head: CgiHead; body: Uint8Array }\n | { kind: 'body' }\n | { kind: 'more' }\n | { kind: 'bad'; reason: string };\n\nconst TOKEN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;\nconst PREFIX = /^[!#$%&'*+.^_`|~0-9A-Za-z-]*$/;\nconst HEADER = /^([!#$%&'*+.^_`|~0-9A-Za-z-]+):[ \\t]*(.*?)[ \\t]*$/;\nconst STATUS = /^([2-5][0-9][0-9])(?:[ \\t]+(.*))?$/;\nconst HOP = new Set([\n 'connection',\n 'keep-alive',\n 'proxy-connection',\n 'te',\n 'trailer',\n 'transfer-encoding',\n 'upgrade',\n]);\n\nexport const REASONS: Record<number, string> = {\n 200: 'OK',\n 201: 'Created',\n 204: 'No Content',\n 302: 'Found',\n 400: 'Bad Request',\n 403: 'Forbidden',\n 404: 'Not Found',\n 405: 'Method Not Allowed',\n 413: 'Payload Too Large',\n 500: 'Internal Server Error',\n 502: 'Bad Gateway',\n 503: 'Service Unavailable',\n 504: 'Gateway Timeout',\n};\n\nexport function scriptOf(path: unknown): { script: string; pathInfo: string } | undefined {\n if (typeof path !== 'string' || !path) return undefined;\n const segments: string[] = [];\n for (const raw of path.split('/')) {\n let segment: string;\n try {\n segment = decodeURIComponent(raw);\n } catch {\n return undefined;\n }\n if (segment === '.' || segment === '..' || /[/\\\\\\0]/.test(segment)) return undefined;\n segments.push(segment);\n }\n const [script, ...rest] = segments as [string, ...string[]];\n if (!script || script.startsWith('.')) return undefined;\n return { script, pathInfo: rest.length ? `/${rest.join('/')}` : '' };\n}\n\nexport function methodOf(method: unknown): string | undefined {\n return typeof method === 'string' && TOKEN.test(method) ? method.toUpperCase() : undefined;\n}\n\nconst clean = (value: string) => value.replace(/[\\r\\n\\0]/g, ' ');\n\nexport function requestHeaders(headers: CgiHeaders): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [name, value] of headers) {\n if (!TOKEN.test(name)) continue;\n const key = name.toLowerCase();\n if (key === 'content-type' || key === 'content-length' || key === 'proxy') continue;\n const at = `HTTP_${key.toUpperCase().replace(/-/g, '_')}`;\n out[at] = out[at] === undefined ? clean(value) : `${out[at]}, ${clean(value)}`;\n }\n return out;\n}\n\nexport interface CgiContext {\n request: CgiRequest;\n script: string;\n pathInfo: string;\n folder: string;\n sprinkle: string;\n owner: string;\n user: string;\n}\n\nexport function cgiEnv(at: CgiContext): Record<string, string> {\n const { request, script, pathInfo, folder } = at;\n const type = request.headers.find(([name]) => name.toLowerCase() === 'content-type')?.[1];\n return {\n ...requestHeaders(request.headers),\n GATEWAY_INTERFACE: 'CGI/1.1',\n SERVER_PROTOCOL: 'HTTP/1.1',\n SERVER_SOFTWARE: 'slicc-agent',\n SERVER_NAME: 'localhost',\n SERVER_PORT: '80',\n REMOTE_ADDR: '127.0.0.1',\n REQUEST_METHOD: request.method,\n QUERY_STRING: request.query,\n SCRIPT_NAME: `/${CGI_DIR}/${script}`,\n SCRIPT_FILENAME: `${folder}/${CGI_DIR}/${script}`,\n DOCUMENT_ROOT: folder,\n REQUEST_URI: `/${CGI_DIR}/${request.path}${request.query ? `?${request.query}` : ''}`,\n PATH_INFO: pathInfo,\n ...(pathInfo ? { PATH_TRANSLATED: `${folder}${pathInfo}` } : {}),\n ...(request.body ? { CONTENT_LENGTH: String(request.body.length) } : {}),\n ...(request.body && type !== undefined ? { CONTENT_TYPE: clean(type) } : {}),\n REMOTE_USER: at.user,\n SLICC_SPRINKLE: at.sprinkle,\n SLICC_OWNER: at.owner,\n ...(request.tab ? { SLICC_TAB: request.tab } : {}),\n };\n}\n\nfunction lineEnd(bytes: Uint8Array, from: number): number {\n return bytes.indexOf(10, from);\n}\n\nfunction decoded(bytes: Uint8Array, from: number, to: number): string {\n const end = to > from && bytes[to - 1] === 13 ? to - 1 : to;\n return new TextDecoder().decode(bytes.subarray(from, end));\n}\n\nexport function headOf(lines: readonly string[]): CgiHead | string {\n let status: number | undefined;\n let statusText = '';\n const headers: CgiHeaders = [];\n for (const line of lines) {\n const [, name, value] = HEADER.exec(line) as unknown as [string, string, string];\n const key = name.toLowerCase();\n if (key === 'status') {\n const found = STATUS.exec(value);\n if (!found) return `bad Status header: ${value}`;\n status = Number(found[1]);\n statusText = found[2] ?? '';\n } else if (!HOP.has(key)) headers.push([name, value]);\n }\n const location = headers.some(([name]) => name.toLowerCase() === 'location');\n const code = status ?? (location ? 302 : 200);\n if (!location && !headers.some(([name]) => name.toLowerCase() === 'content-type'))\n headers.push(['Content-Type', 'text/plain']);\n return { status: code, statusText: statusText || REASONS[code] || '', headers };\n}\n\nexport function parseHead(bytes: Uint8Array, ended: boolean): CgiParsed {\n const lines: string[] = [];\n let at = 0;\n for (;;) {\n const end = lineEnd(bytes, at);\n if (end < 0) break;\n const line = decoded(bytes, at, end);\n at = end + 1;\n if (line === '') {\n if (!lines.length) return { kind: 'body' };\n const head = headOf(lines);\n return typeof head === 'string'\n ? { kind: 'bad', reason: head }\n : { kind: 'head', head, body: bytes.subarray(at) };\n }\n if (!HEADER.test(line)) return { kind: 'body' };\n lines.push(line);\n }\n const rest = decoded(bytes, at, bytes.length);\n if (rest && !HEADER.test(rest) && (ended || !PREFIX.test(rest))) return { kind: 'body' };\n if (!ended) return bytes.length > CGI_LIMITS.head ? { kind: 'body' } : { kind: 'more' };\n if (rest) lines.push(rest);\n if (!lines.length) return { kind: 'body' };\n const head = headOf(lines);\n return typeof head === 'string'\n ? { kind: 'bad', reason: head }\n : { kind: 'head', head, body: new Uint8Array() };\n}\n\nexport function shebang(bytes: Uint8Array): string[] | undefined {\n if (bytes[0] !== 35 || bytes[1] !== 33) return undefined;\n const end = bytes.indexOf(10);\n const line = decoded(bytes, 2, end < 0 ? Math.min(bytes.length, 256) : end).trim();\n const space = line.search(/[ \\t]/);\n if (!line) return undefined;\n if (space < 0) return [line];\n const arg = line.slice(space).trim();\n return arg ? [line.slice(0, space), arg] : [line.slice(0, space)];\n}\n\nexport interface Mode {\n mode?: number;\n uid?: number;\n}\n\nexport function openTo(stat: Mode, uid: number): string | undefined {\n if (stat.mode !== undefined && (stat.mode & 0o022) !== 0)\n return `its group or others can write it (mode ${(stat.mode & 0o777).toString(8)})`;\n if (stat.uid !== undefined && stat.uid !== 0 && stat.uid !== uid)\n return `uid ${stat.uid} owns it, not the sprinkle's owner`;\n return undefined;\n}\n\nexport function inside(path: string, root: string): boolean {\n return path.startsWith(`${root}/`);\n}\n\nexport function tagOf(id: string): string {\n return `${CGI_TAG}${id}`;\n}\n\nexport function sprinklesOf(tags: readonly string[]): string[] {\n return [\n ...new Set(\n tags.filter((tag) => tag.startsWith(CGI_TAG)).map((tag) => tag.slice(CGI_TAG.length))\n ),\n ];\n}\n\nexport function toBase64(bytes: Uint8Array): string {\n let out = '';\n for (let at = 0; at < bytes.length; at += 0x8000)\n out += String.fromCharCode(...bytes.subarray(at, at + 0x8000));\n return btoa(out);\n}\n\nexport function fromBase64(text: string): Uint8Array {\n const raw = atob(text);\n const out = new Uint8Array(raw.length);\n for (let at = 0; at < raw.length; at++) out[at] = raw.charCodeAt(at);\n return out;\n}\n"],
|
|
5
|
+
"mappings": "AAAO,MAAM,UAAU;AAChB,MAAM,UAAU;AAChB,MAAM,aAAa;AAAA,EACxB,OAAO,KAAK;AAAA,EACZ,QAAQ,IAAI,OAAO;AAAA,EACnB,QAAQ,KAAK;AAAA,EACb,MAAM,KAAK;AAAA,EACX,WAAW;AAAA,EACX,UAAU;AAAA,EACV,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,KAAK,OAAO;AACd;AAyBA,MAAM,QAAQ;AACd,MAAM,SAAS;AACf,MAAM,SAAS;AACf,MAAM,SAAS;AACf,MAAM,MAAM,oBAAI,IAAI;AAAA,EAClB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAEM,MAAM,UAAkC;AAAA,EAC7C,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AACP;AAEO,SAAS,SAAS,MAAiE;AACxF,MAAI,OAAO,SAAS,YAAY,CAAC,KAAM,QAAO;AAC9C,QAAM,WAAqB,CAAC;AAC5B,aAAW,OAAO,KAAK,MAAM,GAAG,GAAG;AACjC,QAAI;AACJ,QAAI;AACF,gBAAU,mBAAmB,GAAG;AAAA,IAClC,QAAQ;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