1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import { alias } from "https://esm.town/v/neverstew/alias?v=5";
import { createVal } from "https://esm.town/v/neverstew/createVal?v=6";
import { blob } from "https://esm.town/v/std/blob?v=11";
import { encodeHex } from "jsr:@std/encoding@0.219.1/hex";
const cors = {
"access-control-allow-origin": "*",
"access-control-allow-headers": "*",
};
export default async function(req: Request): Promise<Response> {
try {
if (req.method === "OPTIONS") {
return new Response(null, {
headers: cors,
});
}
if (req.method !== "POST") {
throw new Error("must POST");
}
const { code, token } = await req.json();
const textEncoder = new TextEncoder();
const importedKey = await crypto.subtle.importKey(
"raw",
textEncoder.encode(token),
"PBKDF2",
false,
["deriveBits"],
);
const saltBuffer = textEncoder.encode(Deno.env.get("salt"));
const params = {
name: "PBKDF2",
hash: "SHA-512",
salt: saltBuffer,
iterations: 20000,
};
const key = "play_"
+ encodeHex(await crypto.subtle.deriveBits(params, importedKey, 16 * 8));
await blob.set(key, code);
let val: { id: string; statusCode?: number } = await alias({
username: "websandbox",
valName: key,
});
if (val.statusCode === 404) {
val = await createVal({
token: Deno.env.get("valtown"),
name: key,
code: `export { handle } from "https://esm.town/v/websandbox/run";`,
readme: "This is an anonymous playground. It will [expire](https://www.val.town/v/websandbox/config).",
privacy: "unlisted",
});
await fetch("https://www.val.town/api/trpc/updateVal", {
headers: {
"content-type": "application/json",
authorization: `Bearer ${Deno.env.get("valtown")}`,
},
body: JSON.stringify({ id: val.id, valType: "httpnext" }),
method: "POST",
});
}
if (!val.id) {
return Response.json(
{ error: "failed to create val", details: val },
{
headers: cors,
},
);
}
return Response.json(
{ url: `https://websandbox-${key}.web.val.run` },
{
headers: cors,
},
);
} catch (error) {
return Response.json(
{ error: error.message },
{
headers: cors,
},
);
}
}