cloud / internal-packages / installer / worker / access.jsmain at aacbc74
// access.js — THE CLOUD'S SIDE OF A DEPLOYMENT IT HOLDS NO TOKEN TO: enrol a deployment, ask to be
// let in, leave, forget it, tell the owner an update exists, and show everything the Cloud keeps.
//
// A deployment is a stack of Workers in its owner's own Cloudflare account, with its own identity
// provider at https://iterate.<domain>. The Cloud keeps no long-lived token to it. The two sides
// know each other by keys: the deployment trusts the Cloud's P-256 key (CLOUD_KEY), and the Cloud
// writes to the deployment in one way only, a signed statement that lands in the deployment's log.
// To come in, the Cloud asks with the deployment's device grant, the owner approves on their own
// deployment, and the Cloud gets one access token with a deadline and no refresh. KV deletes that
// token at its deadline. GET /kept lists every row of the KV namespaces, so that nothing hides:
// anybody may read it, and only the operator sees the start of a row's id and a run's own records.
//
// Bindings: SESSIONS (KV), CLOUD_KEY (secret: the private key, one JWK), OPERATOR_TOKEN (secret:
// a stand-in for the operator's sign-in; without it, the operator's pages answer 404).
import { CLAIMS } from "./cloudflare-access.js";
const STATEMENT_TYPE = "application/vnd.iterate.statement+json";
const DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code";
const STATEMENT_LIFE = 5 * 60_000;
const TIMES = [
[900, "15 minutes"],
[3600, "1 hour"],
[14400, "4 hours"],
[86400, "24 hours"],
];
const DOMAIN = /^[a-z0-9-]+(\.[a-z0-9-]+)+$/;
// Where a key that a member allowed may add events (the deployment's `/keys/enrol` confines it):
// everything the Cloud sends lands under this root, and its own notices at CLOUD_PATH.
const SERVICE_ROOT = "/integrations/";
// Who the Cloud is on a deployment (the contract's names): the actor of its key, and its label.
const ACTOR = "iterate-cloud";
const LABEL = "iterate Cloud";
const CLOUD_PATH = "/integrations/cloud";
const enc = new TextEncoder();
// A DEPLOYMENT IS KEPT HERE BY ITS DOMAIN (`enrolled:<domain>`, as service.js and index.js read
// it), and ADDRESSED BY ITS MIND'S NAME: its control plane's hostname, as cloud-clients names it.
// A statement names that hostname (the mind refuses any other), its key is at that hostname's
// `/keys/stack.json`, and the Cloud's held deliveries wait under it. The control plane is
// `iterate.<domain>` unless the mind's config names another (`controlPlaneHostname`); then the
// enrolment's `?mind=` names it, and the record keeps it.
const defaultMindOf = (domain) => `iterate.${domain}`;
const baseOf = (mind) => `https://${mind}`;
/** Whether `mind` is a hostname of `domain`: the domain's owner holds it. */
const ofDomain = (mind, domain) => mind === domain || mind.endsWith(`.${domain}`);
// /enrolled needs no sign-in, so anybody can make the Cloud call iterate.<a domain they name>. Such
// a call follows no redirect (the answer of another host is never read as the deployment's) and
// ends after ten seconds.
const guarded = () => ({ redirect: "manual", signal: AbortSignal.timeout(10_000) });
const b64url = (bytes) =>
btoa(String.fromCharCode(...new Uint8Array(bytes)))
.replace(/\+/g, "-")
.replace(/\//g, "_")
.replace(/=+$/, "");
/** The DSSE bytes a statement's signature covers. Lengths are byte counts. */
export const dsseOf = (body) =>
enc.encode(
`DSSEv1 ${enc.encode(STATEMENT_TYPE).length} ${STATEMENT_TYPE} ${enc.encode(body).length} ${body}`,
);
/** A key id: base64url of the SHA-256 of the SPKI DER bytes. */
export const keyIdOf = async (spki) => b64url(await crypto.subtle.digest("SHA-256", spki));
/** `{ jwk, key }` for this isolate.
* @type {{ jwk: string, key: Promise<{ key: string, publicKey: string, sign: (bytes: BufferSource) => Promise<string> }> } | null} */
let cached = null;
/** The Cloud's key from `env.CLOUD_KEY`: `{ key, publicKey, sign(bytes) }`, where `key` is the key
* id, `publicKey` the SPKI as base64url, and `sign` answers a raw r‖s signature as base64url. */
function cloudKey(env) {
if (!env.CLOUD_KEY) throw new Error("CLOUD_KEY is not set");
if (cached && cached.jwk === env.CLOUD_KEY) return cached.key;
const jwk = JSON.parse(env.CLOUD_KEY);
const algorithm = { name: "ECDSA", namedCurve: "P-256" };
const key = (async () => {
const { d, ...pub } = jwk;
const [secret, open] = await Promise.all([
crypto.subtle.importKey("jwk", jwk, algorithm, false, ["sign"]),
crypto.subtle.importKey("jwk", { ...pub, key_ops: ["verify"] }, algorithm, true, ["verify"]),
]);
const spki = await crypto.subtle.exportKey("spki", open);
return {
key: await keyIdOf(spki),
publicKey: b64url(spki),
sign: async (bytes) =>
b64url(await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, secret, bytes)),
};
})();
cached = { jwk: env.CLOUD_KEY, key };
return key;
}
/** What a deployment's config names to trust the Cloud (`auth.keys`): the Cloud's own key, from
* the same secret that signs, so the two cannot drift apart. */
export const trustOf = async (env) => [
{ actor: ACTOR, publicKey: (await cloudKey(env)).publicKey, label: LABEL, paths: [SERVICE_ROOT] },
];
/** One statement for the mind `mind` (its control plane's hostname), signed by the Cloud's key:
* `{ statement, signature }`. */
async function signed(env, mind, { path, type, payload }) {
const me = await cloudKey(env);
const at = Date.now();
const nonce = b64url(crypto.getRandomValues(new Uint8Array(16)));
const statement = JSON.stringify({
mind,
path,
type,
payload,
at,
expires: at + STATEMENT_LIFE,
nonce,
});
return {
statement,
signature: { format: "p256", key: me.key, sig: await me.sign(dsseOf(statement)) },
};
}
/** Signs one statement and posts it to the mind `mind`, where it lands as an event. Answers
* `{ ok, status, detail }`; `detail` is the deployment's answer as text, `status` 0 when it
* could not be reached. */
async function send(env, mind, event) {
try {
const answer = await fetch(`${baseOf(mind)}/statements`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(await signed(env, mind, event)),
...guarded(),
});
return { ok: answer.ok, status: answer.status, detail: await answer.text() };
} catch (error) {
return { ok: false, status: 0, detail: String(error?.message || error) };
}
}
/** The mind's name of the deployment at `domain`: the one its record keeps, else the default. */
export const mindAt = async (env, domain) =>
(await readJson(env, `enrolled:${domain}`))?.mind || defaultMindOf(domain);
/** Enrols the deployment at `domain`, whose mind is `mind` (its control plane's hostname): reads
* the mind's key, and sends it a statement signed by the Cloud. The mind's acceptance proves
* that it trusts the Cloud's key; only then is the record `enrolled:<domain>` stored, with
* public facts only, and a refusal removes it. The key's id is the SHA-256 of its bytes for
* every format (P-256 SPKI, ML-DSA-65 raw); the Cloud checks nothing the mind signs here, so a
* key that the mind's identity does not list yet (`listed: false`) enrols too. Answers
* `{ ok, record }` or `{ ok, detail, status }` (`status` 0: no key served).
* @returns {Promise<{ ok: true, record: any } | { ok: false, detail: string, status: number }>} */
export async function enrol(env, origin, domain, mind = defaultMindOf(domain)) {
if (!ofDomain(mind, domain))
return { ok: false, status: 400, detail: `${mind} is not a hostname of ${domain}.` };
const served = await fetch(`${baseOf(mind)}/keys/stack.json`, guarded())
.then((r) => (r.ok ? r.json() : null))
.catch(() => null);
if (!served?.key || !served?.publicKey)
return {
ok: false,
status: 0,
detail: `${mind} serves no key at ${baseOf(mind)}/keys/stack.json.`,
};
const publicKey = Uint8Array.from(
atob(served.publicKey.replace(/-/g, "+").replace(/_/g, "/")),
(c) => c.charCodeAt(0),
);
if ((await keyIdOf(publicKey)) !== served.key)
return { ok: false, status: 0, detail: "The mind's key id is not the id of its public key." };
const me = await cloudKey(env);
const event = {
path: CLOUD_PATH,
type: "events.iterate.com/cloud/deployment-enrolled",
payload: { cloud: origin, key: me.key },
};
const sent = await send(env, mind, event);
if (!sent.ok) {
// A deployment that refuses the Cloud's key (403) is not enrolled: its owner removed the key.
// Only the enrolled mind's own refusal says so: /enrolled needs no sign-in, and a 403 from
// another hostname of the domain (`?mind=`) is no word on the mind that the record names.
if (sent.status === 403 && (await mindAt(env, domain)) === mind)
await env.SESSIONS.delete(`enrolled:${domain}`);
return {
ok: false,
status: sent.status,
detail: `${mind} refused (${sent.status || "no answer"}): ${sent.detail}`,
};
}
const record = { domain, mind, key: served.key, publicKey: served.publicKey, at: Date.now() };
await env.SESSIONS.put(`enrolled:${domain}`, JSON.stringify(record));
return { ok: true, record };
}
const readJson = async (env, key) => JSON.parse((await env.SESSIONS.get(key)) || "null");
const form = (url, fields) =>
fetch(url, {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: new URLSearchParams(fields),
});
const ended = (env, domain, state, reason, detail) =>
env.SESSIONS.put(`access:${domain}`, JSON.stringify({ state, reason, detail, at: Date.now() }), {
expirationTtl: 3600, // a declined, expired or refused request is kept one hour
});
/** The row as the page may see it: no token, no device code. */
const shown = (row) => {
if (!row) return null;
const { token, deviceCode, ...rest } = row;
return rest;
};
/** Asks the enrolled deployment at `domain` to let the Cloud in for `seconds` (300 to 86400), with
* `reason` (1 to 300 characters), and puts the request, signed, in the deployment's own log
* (CLOUD_PATH). Any
* failure is stored as `state: "refused"` with no device code. Answers the row as `poll` does. */
export async function ask(env, domain, { seconds, reason }) {
if (!(await env.SESSIONS.get(`enrolled:${domain}`)))
throw new Error("not an enrolled deployment");
seconds = Number(seconds);
reason = String(reason || "").trim();
if (!Number.isInteger(seconds) || seconds < 300 || seconds > 86400)
throw new Error("choose a time");
if (reason.length < 1 || reason.length > 300)
throw new Error("give a reason of 1 to 300 characters");
const mind = await mindAt(env, domain);
const base = baseOf(mind);
const refuse = async (detail) => {
await ended(env, domain, "refused", reason, detail);
return poll(env, domain);
};
try {
const registered = await fetch(`${base}/oauth2/register`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
client_name: LABEL,
token_endpoint_auth_method: "none",
grant_types: [DEVICE_GRANT],
}),
});
const { client_id: clientId } = await registered.json().catch(() => ({}));
if (!registered.ok || !clientId)
return refuse(`The deployment refused to register the Cloud (${registered.status}).`);
// The request proves who asks: a statement by the Cloud's key over exactly what is asked. The
// owner's page then names the Cloud, proven, in place of a name that anyone could give.
const proof = await signed(env, mind, {
path: CLOUD_PATH,
type: "events.iterate.com/cloud/let-in-request-signed",
payload: { client: clientId, seconds, reason },
});
const started = await form(`${base}/oauth2/device_authorization`, {
client_id: clientId,
resource: `${base}/api`,
access_seconds: String(seconds),
reason,
signed: JSON.stringify(proof),
});
const device = await started.json().catch(() => ({}));
if (!started.ok || !device.device_code)
return refuse(
`The deployment refused the request (${started.status}): ${device.error_description || device.error || ""}`,
);
const sent = await send(env, mind, {
path: CLOUD_PATH,
type: "events.iterate.com/cloud/let-in-requested",
payload: {
reason,
seconds,
approve: device.verification_uri_complete,
code: device.user_code,
},
});
if (!sent.ok)
return refuse(`The deployment refused the signed request (${sent.status}): ${sent.detail}`);
const askedAt = Date.now();
const expiresAt = askedAt + Number(device.expires_in || 600) * 1000;
const row = {
state: "asked",
clientId,
deviceCode: device.device_code,
userCode: device.user_code,
approve: device.verification_uri_complete,
reason,
seconds,
askedAt,
expiresAt,
};
await env.SESSIONS.put(`access:${domain}`, JSON.stringify(row), {
expiration: Math.floor(expiresAt / 1000) + 60,
});
return shown(row);
} catch (error) {
return refuse(`The deployment could not be reached: ${String(error?.message || error)}`);
}
}
/** Who the deployment says the bearer of `token` is: one session of its API, a capnweb session
* over a WebSocket, opened for the one question and closed. The token goes in `authenticate`,
* and the calls are not awaited one by one: the root, the session and the mind's `whoami` go in
* one round trip. A deployment that answers no socket says nobody. No redirect is followed, and
* the question ends after ten seconds, as every call to a named deployment does (`guarded`). */
export async function mindWhoami(mind, token) {
const { newWebSocketRpcSession } = await import("capnweb");
const answer = await fetch(`${baseOf(mind)}/api`, {
headers: { upgrade: "websocket" },
redirect: "manual",
});
const socket = answer.webSocket;
if (!socket) return null;
socket.accept();
const api = /** @type {any} */ (newWebSocketRpcSession(socket));
let deadline;
try {
const me = await Promise.race([
api.authenticate(token).mind.whoami(),
new Promise((_, reject) => {
deadline = setTimeout(() => reject(new Error("no answer in ten seconds")), 10_000);
}),
]);
return me?.principal?.email ?? null;
} finally {
clearTimeout(deadline);
// the socket first, with a normal close: capnweb closes an open one with a code of its own
socket.close(1000, "asked");
api[Symbol.dispose]();
}
}
/** Polls the deployment once when the request is `asked`; on a token, asks who we are and stores
* `state: "in"` with a KV expiration at the token's deadline. Answers the row as it now is,
* without its token and device code, or null when there is none. */
export async function poll(env, domain, whoami = mindWhoami) {
const row = await readJson(env, `access:${domain}`);
if (row?.state !== "asked") return shown(row);
if (Date.now() >= row.expiresAt) {
await ended(env, domain, "expired", row.reason, "The owner did not answer in time.");
return poll(env, domain);
}
const mind = await mindAt(env, domain);
const answer = await form(`${baseOf(mind)}/oauth2/token`, {
grant_type: DEVICE_GRANT,
device_code: row.deviceCode,
client_id: row.clientId,
});
const body = await answer.json().catch(() => ({}));
if (!answer.ok) {
if (body.error === "authorization_pending" || body.error === "slow_down") return shown(row);
if (body.error === "access_denied")
await ended(env, domain, "declined", row.reason, "The owner declined.");
else if (body.error === "expired_token")
await ended(env, domain, "expired", row.reason, "The owner did not answer in time.");
else
await ended(
env,
domain,
"refused",
row.reason,
`The deployment refused (${answer.status}): ${body.error || ""}`,
);
return poll(env, domain);
}
const until = Date.now() + Number(body.expires_in || 0) * 1000; // a refresh token, if any, is dropped here
if (!body.access_token || until - Date.now() < 60_000) {
await ended(
env,
domain,
"expired",
row.reason,
"The token ends in under a minute. The Cloud kept nothing.",
);
return poll(env, domain);
}
const as = await whoami(mind, body.access_token).catch(() => null);
const inside = {
state: "in",
clientId: row.clientId,
token: body.access_token,
until,
as,
reason: row.reason,
since: Date.now(),
};
await env.SESSIONS.put(`access:${domain}`, JSON.stringify(inside), {
expiration: Math.floor(until / 1000),
});
return shown(inside);
}
/** Leaves the deployment at `domain` early: revokes the token there (RFC 7009 on the token
* endpoint), then deletes the row whatever the answer. Answers `{ ok, status }`. */
export async function leave(env, domain) {
const row = await readJson(env, `access:${domain}`);
let result = { ok: true, status: 0 };
if (row?.state === "in") {
const answer = await form(`${baseOf(await mindAt(env, domain))}/oauth2/token`, {
token: row.token,
client_id: row.clientId,
}).catch(() => null);
result = { ok: !!answer?.ok, status: answer?.status ?? 0 };
}
await env.SESSIONS.delete(`access:${domain}`);
return result;
}
/** Whether the mind `mind` is gone: its key (`/keys/stack.json`) answers 404 or 410, Cloudflare
* answers 530 (no origin: the host's Worker or DNS record is gone), or the host does not resolve
* or connect. A timeout or another answer (2xx, 5xx) is not proof: false. */
export const isGone = (mind) =>
fetch(`${baseOf(mind)}/keys/stack.json`, guarded())
.then((answer) => [404, 410, 530].includes(answer.status))
.catch((error) => error?.name !== "TimeoutError" && error?.name !== "AbortError");
/** Forgets the deployment at `domain`: leaves it if the Cloud is in, and deletes the Cloud's record
* of it. A deployment that is gone would else stay listed for ever. The deployment itself trusts
* the Cloud's key until its owner removes it there. */
export async function forget(env, domain) {
await leave(env, domain);
await env.SESSIONS.delete(`enrolled:${domain}`);
// "Erase and replace" makes a new deployment at the domain: its installation is another one
await env.SESSIONS.delete(`handover:${domain}`);
}
/** Tells the deployment at `domain` that an update exists. An update is never pushed: the owner
* opens the installer at `origin` and connects Cloudflare again. */
export const announceUpdate = async (env, origin, domain, { commit }) =>
send(env, await mindAt(env, domain), {
path: CLOUD_PATH,
type: "events.iterate.com/cloud/update-announced",
payload: { commit, update: `${origin}/` },
});
// What the visitor said to the Cloud's installation agent goes over as text to quote, never as
// instructions, and the deployment's log is not the place for a long transcript.
const HANDOVER_WORDS = 8_000;
/** Hands a finished installation to the deployment at `domain`: one signed statement at CLOUD_PATH
* that the deployment's onboarding agent reads. `installation` is the Cloud's own id of the
* installation (its conversation's context), `summary` what the installation agent learned.
*
* - Bound to its destination: the statement names the mind's control plane as every statement
* does (the mind refuses one that names another), and the payload names `domain` as
* `destination`, the hostname that the mind's code reads as its own (`itx.url()`).
* - Once: the handover's id is a hash of the deployment and the installation, and the row
* `handover:<domain>` keeps it. A second call for the same installation sends that id again
* only while the deployment has not accepted it, so whoever reads the events counts one
* handover per id. Another installation's is refused.
* - Only to a deployment the Cloud enrolled, so only where a run of the Cloud's own ended.
*
* Answers `{ ok: true, handover, sent }` (`sent` false: accepted before, nothing sent now) or
* `{ ok: false, status, detail }`.
* @returns {Promise<{ ok: true, handover: string, sent: boolean } | { ok: false, status: number, detail: string }>} */
export async function handOver(env, origin, domain, { installation, summary }) {
if (!DOMAIN.test(String(domain || "")))
return { ok: false, status: 400, detail: "Not a domain." };
if (typeof installation !== "string" || !/^[A-Za-z0-9_\-/.:]{1,200}$/.test(installation))
return { ok: false, status: 400, detail: "The installation's id is missing or not an id." };
if (typeof summary !== "string" || !summary.trim() || summary.length > HANDOVER_WORDS)
return {
ok: false,
status: 400,
detail: `The summary is text of 1 to ${HANDOVER_WORDS} characters.`,
};
const enrolled = await readJson(env, `enrolled:${domain}`);
if (!enrolled) return { ok: false, status: 409, detail: "That deployment is not enrolled." };
const key = `handover:${domain}`;
const before = await readJson(env, key);
if (before && before.installation !== installation)
return {
ok: false,
status: 409,
detail: "Another installation was handed over to that deployment.",
};
if (before?.accepted) return { ok: true, handover: before.handover, sent: false };
// The id is the hash of what the handover is: this deployment (its domain and its own key) and
// this installation. So two calls at once, or a call after one that died, send the same id,
// never a second one. It is a name, not a secret.
const row = before || {
handover: b64url(
await crypto.subtle.digest(
"SHA-256",
enc.encode(`${domain}\n${enrolled.key}\n${installation}`),
),
),
installation,
at: Date.now(),
};
if (!before) await env.SESSIONS.put(key, JSON.stringify(row));
const sent = await send(env, enrolled.mind || defaultMindOf(domain), {
path: CLOUD_PATH,
type: "events.iterate.com/cloud/installation-handed-over",
payload: {
handover: row.handover,
destination: domain,
cloud: origin,
installation,
summary,
},
});
if (!sent.ok)
return {
ok: false,
status: sent.status === 403 ? 403 : 502,
detail: `The deployment refused (${sent.status}): ${sent.detail}`,
};
await env.SESSIONS.put(key, JSON.stringify({ ...row, accepted: Date.now() }));
return { ok: true, handover: row.handover, sent: true };
}
/** What each KV prefix holds, in one sentence. */
const KINDS = {
"s:": "A person's sign-in to the installer: who they are at Cloudflare, and their accounts' names. No token.",
"t:": "The Cloudflare access token of a sign-in, until Cloudflare ends it or a deploy takes it.",
"state:": "A sign-in to Cloudflare in progress: its PKCE verifier, kept ten minutes.",
"created:":
"The Cloudflare account the installer made for a person, so that a new tab does not make another. Gone once a consent for it connects it, or when they make another.",
"dep:":
"That a deploy run exists for an account and a domain, its owner's address, and when it started.",
"enrolled:":
"A deployment's public key. The deployment accepted a statement signed by the Cloud.",
"access:":
"The Cloud's request to be let in to a deployment, and while it is in, its access token.",
"handover:":
"That the Cloud handed an installation over to a deployment's onboarding agent: the handover's id, the installation's id, and when. Not what was said.",
// the relay's rows (mcp-relay.js), written by @cloudflare/workers-oauth-provider into a
// namespace of the relay's own (RELAY), where there is a relay
"client:": "An app that registered itself at the relay: its name and where it sends people back.",
"grant:":
"An app's connection to one deployment through the relay. The deployment's tokens are in it, encrypted under a key that only the app's own token unwraps.",
"token:":
"The hash of a token the relay gave an app, and the key to its connection, wrapped by that token.",
"transaction:": "A sign-in through the relay that is under way, encrypted. Ten minutes.",
"registrations:":
"How many apps registered at the relay in ten minutes, in all and from one address. Twenty minutes.",
};
/** Every key of the installer's KV namespace, and of the relay's where there is one. */
async function* keysOf(env) {
for (const namespace of [env.SESSIONS, env.RELAY]) {
if (!namespace) continue;
let cursor;
do {
const page = await namespace.list({ cursor });
yield* page.keys;
cursor = page.list_complete ? null : page.cursor;
} while (cursor);
}
}
/** Every row of both namespaces: `{ records: [{ key, kind, what, reaches, until }] }`. `key` is
* the row's prefix alone; with `ids` (the operator's view) it has the id after the prefix, cut to
* six characters: an id is a domain, an account id or a session's id, and the page without a
* sign-in shows no part of one. `reaches` is "nothing", "a Cloudflare account" or
* "a deployment"; `until` (epoch ms) is when that ends, or when KV deletes the row. */
export async function kept(env, { ids = false } = {}) {
const records = [];
for await (const { name, expiration } of keysOf(env)) {
const kind = Object.keys(KINDS).find((prefix) => name.startsWith(prefix));
const id = kind ? name.slice(kind.length) : "";
let reaches = "nothing";
let until = expiration ? expiration * 1000 : null;
if (kind === "t:") reaches = "a Cloudflare account";
if (kind === "grant:") reaches = "a deployment, and only with the app's own token";
if (kind === "access:") {
const value = await readJson(env, name);
if (value?.state === "in") [reaches, until] = ["a deployment", value.until];
}
records.push({
key: !ids
? kind || "unknown"
: kind
? `${kind}${id.slice(0, 6)}${id.length > 6 ? "…" : ""}`
: `${name.slice(0, 6)}…`,
kind: kind ? kind.slice(0, -1) : "unknown",
what: kind ? KINDS[kind] : "unknown",
reaches,
until,
});
}
return { records };
}
// ── pages ───────────────────────────────────────────────────────────────────────────────────────
const esc = (value) =>
String(value ?? "").replace(
/[&<>"']/g,
(c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c],
);
const utc = (ms) =>
ms ? new Date(ms).toISOString().slice(0, 16).replace("T", " ") + " UTC" : "no end";
/** @type {(title: string, body: string, options?: { status?: number, refresh?: number }) => Response} */
const page = (title, body, { status = 200, refresh } = {}) =>
new Response(
`<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width">${refresh ? `<meta http-equiv="refresh" content="${refresh}">` : ""}<title>${esc(title)}</title><style>body{font:16px/1.5 system-ui,sans-serif;max-width:40rem;margin:2rem auto;padding:0 1rem}table{border-collapse:collapse;width:100%;font-size:14px}td,th{border-bottom:1px solid #ddd;padding:.3rem;text-align:left;vertical-align:top}form{margin:.5rem 0}code{word-break:break-all}</style><h1>${esc(title)}</h1>${body}`,
{
status,
headers: {
"content-type": "text/html; charset=utf-8",
// no page of these may be shown in a frame: a frame is how another site gets a click
"content-security-policy": "frame-ancestors 'none'",
"x-frame-options": "DENY",
},
},
);
const go = (location, status, cookie) =>
new Response(null, {
status,
// oxlint-disable-next-line iterate/simple-truthiness-check -- a header with the value undefined is sent as the text "undefined"
headers: { location, ...(cookie && { "set-cookie": cookie }) },
});
/** Compares two strings in constant time (over their SHA-256 hashes). */
export async function same(a, b) {
const [x, y] = await Promise.all(
[a, b].map(async (s) => new Uint8Array(await crypto.subtle.digest("SHA-256", enc.encode(s)))),
);
return x.reduce((diff, byte, i) => diff | (byte ^ y[i]), 0) === 0;
}
// The operator's cookie. `__Host-`: a browser takes it only from this host itself, over HTTPS, for
// every path, so no other host under the same domain can set one.
const OPERATOR_COOKIE = "__Host-operator";
const SIGN_IN = `<form method="post" action="/access/sign-in"><input type="password" name="operator" placeholder="The operator's token" autocomplete="off" required> <button>Sign in</button></form>`;
/** True when the request carries the operator's cookie. */
async function operatorOf(request, env) {
if (!env.OPERATOR_TOKEN) return false;
const cookie = new RegExp(`(?:^|;\\s*)${OPERATOR_COOKIE}=([^;]*)`).exec(
request.headers.get("cookie") || "",
)?.[1];
if (!cookie) return false;
let given;
try {
given = decodeURIComponent(cookie);
} catch {
return false;
}
return same(given, env.OPERATOR_TOKEN);
}
/** Every key of the KV namespace under `prefix`, without the prefix. */
async function listed(env, prefix) {
const names = [];
let cursor;
do {
const list = await env.SESSIONS.list({ prefix, cursor });
names.push(...list.keys.map((k) => k.name.slice(prefix.length)));
cursor = list.list_complete ? null : list.cursor;
} while (cursor);
return names;
}
function accessSection(domain, row) {
const h = `<h2>${esc(domain)}</h2>`;
const hidden = `<input type="hidden" name="domain" value="${esc(domain)}">`;
const announce = `<form method="post" action="/access/announce-update">${hidden}<input name="commit" placeholder="commit" required> <button>Tell the owner an update exists</button></form>`;
let state = "";
if (row?.state === "asked")
state = `<p>Waiting for the owner. The request is in their deployment, signed by the Cloud. The code is <code>${esc(row.userCode)}</code>. Only a member who is signed in there can approve it, at <a href="${esc(row.approve)}">${esc(row.approve)}</a>.</p>`;
else if (row?.state === "in")
state = `<p>Let in as ${esc(row.as || "an unknown principal")} until ${esc(utc(row.until))}. This cannot be renewed.</p><form method="post" action="/access/leave">${hidden}<button>Leave now</button></form>`;
else {
// a request that ended: its detail is a whole sentence that says how
if (row) state = `<p>${esc(row.detail)}</p>`;
state += `<form method="post" action="/access/ask">${hidden}<input name="reason" maxlength="300" placeholder="Why the Cloud must come in" required> <select name="seconds">${TIMES.map(([s, label]) => `<option value="${s}">${label}</option>`).join("")}</select> <button>Ask to be let in</button></form>`;
}
const forgetting = `<form method="post" action="/access/forget">${hidden}<button>Forget this deployment</button></form>`;
return h + state + announce + forgetting;
}
/** THE ENROLMENT'S FIRST PAGE: two steps, since the mind sends the browser back to `done` only
* when the Cloud's host is one of the mind's own; the second is a link the person can always
* press. */
async function enrolPage(env, origin, domain, mind, done) {
const me = await cloudKey(env);
// `cloud`: the mind gives the key the Cloud's name only once it read the same key at
// `<cloud>/.well-known/iterate-cloud`, and shows that host to the member who allows it
const query = new URLSearchParams({
actor: ACTOR,
label: LABEL,
publicKey: me.publicKey,
paths: SERVICE_ROOT,
cloud: origin,
next: done,
});
return page(
`Enrol ${domain}`,
`<p>The Cloud keeps no token to your mind. The two know each other by keys.</p>
<ol><li><a href="${esc(`${baseOf(mind)}/keys/enrol?${query}`)}">Allow the Cloud's key on ${esc(mind)}</a>. You sign in there as a member, and press your passkey. With the key, the Cloud can add events under <code>${SERVICE_ROOT}</code>, and nothing else.</li>
<li><a href="${esc(done)}">Finish here</a>, if your mind did not bring you back.</li></ol>
<p>Your mind's address: ${esc(mind)}. If its control plane has another hostname, add <code>&mind=<that hostname></code> to this page's address.</p>
<p>The Cloud's key: <code>${esc(me.key)}</code></p>`,
);
}
/** WHY `/enrolled` DID NOT ENROL, AND WHAT THE PERSON DOES NEXT, by what the mind answered:
* nothing at its key's address (`status` 0), a refusal of the Cloud's key (403), or anything
* else. */
function notEnrolledPage(origin, domain, mind, { status, detail }, done) {
const first = `${origin}/enrol?${new URLSearchParams(new URL(done).searchParams)}`;
const next =
status === 403
? `<p>${esc(mind)} does not trust the Cloud's key yet. Go back to <a href="${esc(first)}">the first step</a>, allow the key there with your passkey, then open <a href="${esc(done)}">this page</a> again.</p>`
: status === 0
? `<p>The Cloud found no mind at ${esc(mind)}. Check that ${esc(domain)} is your mind's domain. If your mind's control plane has another hostname, open <a href="${esc(first)}">the first step</a> with <code>&mind=<that hostname></code> added to its address.</p>`
: `<p>${esc(mind)} did not take the Cloud's statement. <a href="${esc(done)}">Try again</a> in a minute.</p>`;
return page("Not enrolled yet", `${next}<p>What the Cloud saw: ${esc(detail)}</p>`, {
status: 409,
});
}
/** Answers the Cloud's access routes, or null for any other path. `options.whoami` replaces the
* capnweb call that asks a deployment who the Cloud is (a test passes its own).
* `options.onEnrolled(domain, record)` runs after a deployment enrolled on `/enrolled`: the
* Cloud's Worker that holds webhooks for a deployment delivers them then.
* @param {Request} request
* @param {any} env
* @param {{ whoami?: typeof mindWhoami, onEnrolled?: (domain: string, record: any) => unknown }} [options] */
export async function handle(request, env, { whoami = mindWhoami, onEnrolled } = {}) {
const url = new URL(request.url);
const path = url.pathname;
const domainOf = (value) => (DOMAIN.test(String(value || "")) ? String(value) : null);
if ((path === "/enrol" || path === "/enrolled") && request.method === "GET") {
const domain = domainOf(url.searchParams.get("domain"));
// the mind's control plane: `iterate.<domain>`, or the hostname of the domain that `?mind=` names
const named = url.searchParams.get("mind");
const mind = named ? domainOf(named) : defaultMindOf(String(domain));
if (!domain || !mind || !ofDomain(mind, domain))
return page(
"Not a domain",
"<p>Give your mind's domain as a plain hostname, such as example.com. If its control plane is not iterate.<domain>, add mind=<that hostname>.</p>",
{ status: 400 },
);
const done = `${url.origin}/enrolled?${new URLSearchParams(named ? { domain, mind } : { domain })}`;
if (path === "/enrol") return enrolPage(env, url.origin, domain, mind, done);
const result = await enrol(env, url.origin, domain, mind);
if (!result.ok) return notEnrolledPage(url.origin, domain, mind, result, done);
await onEnrolled?.(domain, result.record);
const me = await cloudKey(env);
return page(
"Enrolled",
`<p><strong>${esc(domain)} trusts the Cloud's key, and the Cloud knows the mind's key. Events for its connected accounts are delivered from now.</strong></p>
<p>There is nothing more to do here: you can close this page.</p>
<p>The mind: ${esc(mind)}. Its key: <code>${esc(result.record.key)}</code>. The Cloud's key: <code>${esc(me.key)}</code>.</p>`,
);
}
if (path === "/kept" && request.method === "GET") {
// Anybody may read this page. Only the operator sees the start of each row's id, and each run's
// own records: to read those wakes the object of every run.
const operator = await operatorOf(request, env);
const { records } = await kept(env, { ids: operator });
// each deploy run keeps its state in an object of its own (./deploy-run.js): listed too
// and the object that keeps which sign-in's token is spoken for (cloudflare-access.js)
for (const run of env.DEPLOYER && operator ? [CLAIMS, ...(await listed(env, "dep:"))] : []) {
const held = await env.DEPLOYER.getByName(run).kept();
for (const r of held.records)
records.push({
key: `${run === CLAIMS ? CLAIMS : `run ${run.slice(0, 6)}…`} ${r.key}`,
what: `${r.where}. ${r.what}`,
reaches: "nothing",
until: null,
});
}
const reach = (what) => {
const count = records.filter((r) => r.reaches === what).length;
return `${count} ${count === 1 ? "row reaches" : "rows reach"} ${what}`;
};
const rows = records
.map(
(r) =>
`<tr><td><code>${esc(r.key)}</code></td><td>${esc(r.what)}</td><td>${esc(r.reaches)}</td><td>${esc(r.until ? utc(r.until) : "")}</td></tr>`,
)
.join("");
return page(
"What the Cloud keeps",
`<p>${reach("a deployment")}, and ${reach("a Cloudflare account")}.</p>${operator ? "" : "<p>Each deploy run (a row of the kind dep) also keeps its state and the end of its log in an object of its own. The operator's view of this page lists those records, and the start of each row's id.</p>"}<table><tr><th>Key</th><th>What</th><th>Reaches</th><th>Until</th></tr>${rows}</table>`,
);
}
if (path !== "/access" && !path.startsWith("/access/")) return null;
// ── the operator's pages ──
if (!env.OPERATOR_TOKEN) return new Response("Not found\n", { status: 404 });
// The token goes in a form's body, never in an address: an address is in the Worker's logs and
// in the browser's history. An address that carries one is refused unread.
if (url.searchParams.has("operator"))
return page(
"Refused",
`<p>The operator's token does not go in the address. Sign in with this form.</p>${SIGN_IN}`,
{ status: 400 },
);
if (request.method === "POST" && request.headers.get("origin") !== url.origin)
return page("Refused", "<p>This form came from another site.</p>", { status: 403 });
if (path === "/access/sign-in" && request.method === "POST") {
const given = String((await request.formData()).get("operator") || "");
if (!(await same(given, env.OPERATOR_TOKEN)))
return page("Refused", `<p>That is not the operator's token.</p>${SIGN_IN}`, { status: 403 });
return go(
"/access",
303,
`${OPERATOR_COOKIE}=${encodeURIComponent(given)}; Path=/; HttpOnly; Secure; SameSite=Strict`,
);
}
if (!(await operatorOf(request, env)))
return page("Refused", `<p>Sign in as an operator first.</p>${SIGN_IN}`, { status: 403 });
if (request.method === "POST") {
const fields = await request.formData();
const domain = domainOf(fields.get("domain"));
if (!domain || !(await env.SESSIONS.get(`enrolled:${domain}`)))
return page("Not enrolled", "<p>That deployment is not enrolled.</p>", { status: 400 });
if (path === "/access/ask")
await ask(env, domain, { seconds: fields.get("seconds"), reason: fields.get("reason") });
else if (path === "/access/leave") await leave(env, domain);
else if (path === "/access/forget") await forget(env, domain);
else if (path === "/access/announce-update")
await announceUpdate(env, url.origin, domain, { commit: String(fields.get("commit") || "") });
else return new Response("Not found\n", { status: 404 });
return go("/access", 303);
}
if (path !== "/access" || request.method !== "GET")
return new Response("Not found\n", { status: 404 });
const domains = await listed(env, "enrolled:");
const rows = await Promise.all(domains.map((domain) => poll(env, domain, whoami)));
const sections = domains.map((domain, i) => accessSection(domain, rows[i])).join("");
return page("Access to deployments", sections || "<p>No deployment is enrolled.</p>", {
refresh: rows.some((row) => row?.state === "asked") ? 6 : undefined,
});
}