cloud / internal-packages / cloud-clients / dev / fake-x / worker.jsmain at aacbc74
// dev/fake-x/worker.js — A FAKE X FOR THE DEV CLOUD'S BOT: X's OAuth and the five API calls the
// bot makes (../../src/bot.ts), at X's own paths, plus controls for a check. The pet shop's X fake
// (internal-packages/dummy-petshop) signs people in and names them; it has no messages. This one
// has. It consents at once, as the person the authorize link names, and it keeps everything in one
// Durable Object. A fixture: no secret here is a real one.
//
// GET /i/oauth2/authorize?client_id&redirect_uri&state&code_challenge[&user][&username]
// POST /2/oauth2/token authorization_code | refresh_token, HTTP Basic; a
// refresh token is spent on use, as X spends one
// GET /2/users/me whose token it is
// GET /2/dm_events direct messages the token's user is in, newest first
// GET /2/users/<id>/mentions[?since_id] posts that mention the user, newest first
// POST /2/dm_conversations/with/<id>/messages a direct message from the token's user
// POST /2/tweets a post from the token's user
// POST /__test-controls/dm { from, to, text } a direct message arrives
// POST /__test-controls/mention { from, to, text } a post mentions someone
// GET /__test-controls/sent?by=<user id> what that user sent, newest first
// POST /__test-controls/lose-a-refresh the next refresh spends its token,
// issues the new pair, and answers 500: an answer lost
// on its way, so the token that asked is refused after
import { DurableObject } from "cloudflare:workers";
const CLIENT = { id: "fake-x-client", secret: "fake-x-client-secret" };
const json = (body, status = 200) => Response.json(body, { status });
const random = () => crypto.randomUUID().replaceAll("-", "");
const sha256 = async (text) =>
Buffer.from(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text))).toString(
"base64url",
);
export class FakeX extends DurableObject {
async fetch(request) {
const url = new URL(request.url);
const key = `${request.method} ${url.pathname}`;
const store = this.ctx.storage;
const query = Object.fromEntries(url.searchParams);
const nextId = async () => {
const id = ((await store.get("id")) || 1_000_000) + 1;
await store.put("id", id);
return String(id);
};
if (key === "GET /i/oauth2/authorize") {
if (query.client_id !== CLIENT.id || !query.code_challenge)
return json({ error: "invalid_request" }, 400);
const code = random();
await store.put(`code:${code}`, {
user: { id: query.user || "424242", username: query.username || "someone" },
redirectUri: query.redirect_uri,
challenge: query.code_challenge,
});
const back = new URL(query.redirect_uri);
back.searchParams.set("code", code);
back.searchParams.set("state", query.state || "");
return Response.redirect(back.href, 302);
}
if (key === "POST /2/oauth2/token") {
const form = Object.fromEntries(new URLSearchParams(await request.text()));
if (request.headers.get("authorization") !== `Basic ${btoa(`${CLIENT.id}:${CLIENT.secret}`)}`)
return json({ error: "invalid_client" }, 401);
let user;
if (form.grant_type === "authorization_code") {
const pending = await store.get(`code:${form.code}`);
await store.delete(`code:${form.code}`);
if (
!pending ||
pending.redirectUri !== form.redirect_uri ||
pending.challenge !== (await sha256(form.code_verifier || ""))
)
return json({ error: "invalid_grant" }, 400);
({ user } = pending);
} else if (form.grant_type === "refresh_token") {
user = await store.get(`refresh:${form.refresh_token}`);
await store.delete(`refresh:${form.refresh_token}`);
if (!user) return json({ error: "invalid_grant" }, 400);
} else return json({ error: "unsupported_grant_type" }, 400);
const [access, refresh] = [random(), random()];
await store.put({ [`access:${access}`]: user, [`refresh:${refresh}`]: user });
if (form.grant_type === "refresh_token" && (await store.delete("lose-a-refresh")))
return json({ error: "the answer is lost, on a check's word" }, 500);
return json({
token_type: "bearer",
access_token: access,
refresh_token: refresh,
expires_in: 7200,
});
}
if (key === "POST /__test-controls/dm" || key === "POST /__test-controls/mention") {
const { from, to, text } = await request.json();
const id = await nextId();
const row = {
id,
from: String(from),
to: String(to),
text: String(text),
at: new Date().toISOString(),
};
await store.put(`${key.endsWith("dm") ? "dm" : "post"}:${id.padStart(12, "0")}`, row);
return json(row, 201);
}
if (key === "POST /__test-controls/lose-a-refresh") {
await store.put("lose-a-refresh", true);
return json({ loses: "the next refresh" }, 201);
}
if (key === "GET /__test-controls/sent") {
const rows = [
...(await store.list({ prefix: "dm:" })).values(),
...(await store.list({ prefix: "post:" })).values(),
];
return json(
rows.filter((row) => row.from === query.by).sort((a, b) => Number(b.id) - Number(a.id)),
);
}
const me = await store.get(
`access:${(request.headers.get("authorization") || "").replace(/^Bearer /, "")}`,
);
if (!me) return json({ title: "Unauthorized" }, 401);
if (key === "GET /2/users/me")
return json({ data: { id: me.id, username: me.username, name: me.username } });
if (key === "GET /2/dm_events") {
const rows = [...(await store.list({ prefix: "dm:", reverse: true, limit: 50 })).values()];
return json({
data: rows
.filter((row) => row.from === me.id || row.to === me.id)
.map((row) => ({
id: row.id,
event_type: "MessageCreate",
text: row.text,
sender_id: row.from,
created_at: row.at,
dm_conversation_id: [row.from, row.to].sort().join("-"),
})),
meta: {},
});
}
const mentions = /^\/2\/users\/([^/]+)\/mentions$/.exec(url.pathname);
if (request.method === "GET" && mentions) {
const rows = [...(await store.list({ prefix: "post:", reverse: true, limit: 50 })).values()];
return json({
data: rows
.filter(
(row) =>
row.to === mentions[1] &&
(!query.since_id || Number(row.id) > Number(query.since_id)),
)
.map((row) => ({
id: row.id,
text: row.text,
author_id: row.from,
created_at: row.at,
conversation_id: row.id,
})),
meta: {},
});
}
const message = /^\/2\/dm_conversations\/with\/([^/]+)\/messages$/.exec(url.pathname);
if (request.method === "POST" && message) {
const id = await nextId();
await store.put(`dm:${id.padStart(12, "0")}`, {
id,
from: me.id,
to: message[1],
text: String((await request.json()).text),
at: new Date().toISOString(),
});
return json(
{ data: { dm_conversation_id: [me.id, message[1]].sort().join("-"), dm_event_id: id } },
201,
);
}
if (key === "POST /2/tweets") {
const body = await request.json();
const id = await nextId();
await store.put(`post:${id.padStart(12, "0")}`, {
id,
from: me.id,
to: "",
text: String(body.text),
inReplyTo: body.reply?.in_reply_to_tweet_id,
at: new Date().toISOString(),
});
return json({ data: { id, text: body.text } }, 201);
}
return json({ title: "Not Found" }, 404);
}
}
export default {
fetch: (request, env) => env.FAKE_X.get(env.FAKE_X.idFromName("x")).fetch(request),
};