cloud / internal-packages / installer / pretend / worker.jsmain at aacbc74
// The pretend Cloudflare, deployed: world.js behind a sign-in that takes an email and nothing else.
// Each email has its own world (a Durable Object, named by a hash of the email), so two people who
// try the wizard don't meet. A browser says who it is with a cookie; the wizard says it with the
// tokens the world gave it, which carry the world's key.
import { DurableObject } from "cloudflare:workers";
import { handle, hexId, worldFor } from "./world.js";
import * as pages from "./pages.js";
const TOKEN = /^p_([0-9a-f]{32})_/;
const html = (body, status = 200, headers = {}) =>
new Response(body, {
status,
headers: {
"content-type": "text/html; charset=utf-8",
"cache-control": "no-store",
...headers,
},
});
const json = (value, status = 200) =>
new Response(JSON.stringify(value), {
status,
headers: { "content-type": "application/json", "cache-control": "no-store" },
});
const cookie = (email) =>
`pretend_email=${encodeURIComponent(email)}; Path=/; Max-Age=${email ? 30 * 24 * 3600 : 0}; HttpOnly; Secure; SameSite=Lax`;
const emailOf = (request) => {
const m = /(?:^|;\s*)pretend_email=([^;]+)/.exec(request.headers.get("cookie") || "");
try {
return m ? cleanEmail(decodeURIComponent(m[1])) : null;
} catch {
return null;
}
};
const cleanEmail = (value) => {
const email = String(value || "")
.trim()
.toLowerCase();
return email.length <= 120 && /^[a-z0-9._+-]+@[a-z0-9.-]+\.[a-z]{2,}$/.test(email) ? email : null;
};
/** Where to go after signing in: a path on this site, never another site. */
const safeNext = (next) =>
typeof next === "string" && /^\/(?!\/)/.test(next) && !next.includes("\\") ? next : "/";
const keyOf = async (email) =>
[...new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(email)))]
.map((b) => b.toString(16).padStart(2, "0"))
.join("")
.slice(0, 32);
function toWorld(env, key, request, email) {
const headers = new Headers(request.headers);
headers.set("x-pretend-key", key);
if (email) headers.set("x-pretend-email", email);
else headers.delete("x-pretend-email");
return env.WORLDS.get(env.WORLDS.idFromName(key)).fetch(
new Request(request, { headers, redirect: "manual" }),
);
}
export default {
async fetch(request, env) {
const url = new URL(request.url);
const path = url.pathname;
const view = { world: null, wizard: env.WIZARD || null, deployed: true };
if (path === "/robots.txt")
return new Response("User-agent: *\nDisallow: /\n", {
headers: { "content-type": "text/plain" },
});
if (path === "/favicon.ico") return new Response(null, { status: 204 });
if (path === "/login") {
if (request.method !== "POST")
return html(pages.login(view, safeNext(url.searchParams.get("next"))));
const form = new URLSearchParams(await request.text());
const next = safeNext(form.get("next"));
const email = cleanEmail(form.get("email"));
if (!email)
return html(
pages.login(view, next, "That doesn't look like an email. Try you+ready@example.com."),
400,
);
return new Response(null, {
status: 303,
headers: { location: next, "set-cookie": cookie(email) },
});
}
if (path === "/logout")
return new Response(null, {
status: 303,
headers: { location: "/", "set-cookie": cookie("") },
});
// the wizard's calls say whose world they are for in the token
if (path.startsWith("/client/v4") || path === "/_pretend/deployed") {
const key = TOKEN.exec(
/^Bearer (\S+)$/.exec(request.headers.get("authorization") || "")?.[1] || "",
)?.[1];
if (!key)
return json(
{
success: false,
errors: [{ code: 10000, message: "Authentication error" }],
messages: [],
result: null,
},
401,
);
return toWorld(env, key, request, null);
}
if (path === "/oauth2/token") {
const form = new URLSearchParams(await request.clone().text());
const key = TOKEN.exec(form.get("code") || "")?.[1];
if (!key) return json({ error: "invalid_grant" }, 400);
return toWorld(env, key, request, null);
}
if (path === "/oauth2/revoke") {
const form = new URLSearchParams(await request.clone().text());
const key = TOKEN.exec(form.get("token") || "")?.[1];
return key ? toWorld(env, key, request, null) : json({});
}
// a person's browser says who it is with the cookie from /login
const email = emailOf(request);
if (!email) {
if (path === "/" && request.method === "GET") return html(pages.home(view, url.searchParams));
return new Response(null, {
status: 302,
headers: { location: `/login?next=${encodeURIComponent(path + url.search)}` },
});
}
return toWorld(env, await keyOf(email), request, email);
},
};
/** One email's Cloudflare. It starts as the email's tags say (worldFor) and keeps what happens to it. */
export class World extends DurableObject {
async fetch(request) {
const key = request.headers.get("x-pretend-key");
const email = request.headers.get("x-pretend-email");
let world = this.world || (await this.ctx.storage.get("world"));
if (!world) {
// only a signed-in browser makes a world: a token for a world that is gone is just refused
if (!email)
return new URL(request.url).pathname.startsWith("/oauth2/")
? json({ error: "invalid_grant" }, 400)
: json(
{
success: false,
errors: [{ code: 10000, message: "Authentication error" }],
messages: [],
result: null,
},
401,
);
world = worldFor(email, key);
}
this.world = world;
const answer = await handle(world, request, {
mint: () => `p_${key}_${hexId()}`,
quoteNeeds: "card",
activateAfter: 20_000,
wizard: this.env.WIZARD || null,
deployed: true,
// a new person as far as the wizard can tell: it remembers things by Cloudflare user id
reset: () => worldFor(world.user.email, hexId()),
});
// a world lives for a long time: keep only the newest of what piles up
const newest = (map, n) => Object.fromEntries(Object.entries(map).slice(-n));
world.tokens = newest(world.tokens, 40);
world.codes = newest(world.codes, 10);
world.created = newest(world.created, 40);
await this.ctx.storage.put("world", world);
return answer;
}
}