capsite/webapp: rotate the cookie in place
The cookie moves out of the immutable init into a MapStore (key shape "cookie", value M.string()) in the instance's DO storage. Handles get its read-only view via the new WebApp.withHeaderMap, which reads at every send, so a rotation reaches handles already out and the webapp id, and with it the cache's wiring, stays put (checklist goal 6). Whoever holds the id can rotate, by RPC (WebAppFactory.cookies(id)) or POST /at/<id>/cookie; the diigo account owner revokes by logging out. Durable state: instances minted earlier keep the cookie in init.headers. The first handle() moves it to the store and rewrites init without it, in one transaction. Code from before this commit would then see no cookie, so rolling back past it needs the reverse move. webapp gains a package.json and a vitest workerd pool for the tests. Generated-by: Claude Opus 5.5
This commit is contained in:
1 parent
9179bdbf38
commit
10414c2ce6
9 files changed
+2512
-14
No files matched your search
+115
-10
@@ -7,13 +7,21 @@
|
||||
// DurableObjectNamespace/DurableObjectId/DurableObjectStub are ambient types
|
||||
// in worker-configuration.d.ts (not exports of "cloudflare:workers")
|
||||
import { RpcTarget, DurableObject, WorkerEntrypoint } from "cloudflare:workers";
|
||||
import { M } from "../../lib/src/patterns.js";
|
||||
import { makeMapStore, type MapStore } from "../../lib/src/store.js";
|
||||
|
||||
export type Query = Record<string, string | number>;
|
||||
type Headers = Record<string, string>;
|
||||
|
||||
/** headers looked up at each send, e.g. a store's read-only view: whoever
|
||||
* holds the store can rotate a credential under handles already out */
|
||||
export type HeaderMap = { entries(): [string, unknown][] | Promise<[string, unknown][]> };
|
||||
|
||||
/**
|
||||
* init for a new instance — fixed at creation. An instance is immutable
|
||||
* authority: no re-config methods, only attenuation via the fluent chain.
|
||||
* init for a new instance — fixed at creation, except that a `cookie`
|
||||
* header goes to the instance's rotatable cookie store (see
|
||||
* {@link WebAppDo}). Otherwise immutable authority: no re-config methods,
|
||||
* only attenuation via the fluent chain.
|
||||
*/
|
||||
export interface WebAppInit {
|
||||
url: string;
|
||||
@@ -29,6 +37,7 @@ export interface FluentGet {
|
||||
withHeaders(h: Headers): FluentGet;
|
||||
withHeader(key: string, value: string): FluentGet;
|
||||
cookies(cookie: string): FluentGet;
|
||||
withHeaderMap(map: HeaderMap): FluentGet;
|
||||
get(): Promise<string>;
|
||||
post(body: string): Promise<string>;
|
||||
}
|
||||
@@ -57,16 +66,19 @@ export interface FluentGet {
|
||||
export class WebApp extends RpcTarget implements FluentGet {
|
||||
#url: string;
|
||||
#headers: Headers;
|
||||
#maps: readonly HeaderMap[];
|
||||
#send: (url: string, headers: Headers, method: "GET" | "POST", body?: string) => Promise<string>;
|
||||
|
||||
constructor(
|
||||
url: string,
|
||||
headers: Headers,
|
||||
maps: readonly HeaderMap[],
|
||||
send: (url: string, headers: Headers, method: "GET" | "POST", body?: string) => Promise<string>,
|
||||
) {
|
||||
super();
|
||||
this.#url = url;
|
||||
this.#headers = headers;
|
||||
this.#maps = maps;
|
||||
this.#send = send;
|
||||
}
|
||||
|
||||
@@ -85,13 +97,13 @@ export class WebApp extends RpcTarget implements FluentGet {
|
||||
throw new Error(`pathjoin: ${ref} not within ${hereNoQuery.href}`);
|
||||
}
|
||||
const baseParams: Query = Object.fromEntries(here.searchParams);
|
||||
return new WebApp(unionQuery(there.href, baseParams), this.#headers, this.#send);
|
||||
return new WebApp(unionQuery(there.href, baseParams), this.#headers, this.#maps, this.#send);
|
||||
}
|
||||
|
||||
/** Union headers, flower-style (see {@link WebApp}): a shared key with a
|
||||
* different value throws; the same value is fine. */
|
||||
withHeaders(h: Headers): WebApp {
|
||||
return new WebApp(this.#url, unionHeaders(this.#headers, h), this.#send);
|
||||
return new WebApp(this.#url, unionHeaders(this.#headers, h), this.#maps, this.#send);
|
||||
}
|
||||
|
||||
/** one key, flower-style (see {@link WebApp}) */
|
||||
@@ -105,15 +117,34 @@ export class WebApp extends RpcTarget implements FluentGet {
|
||||
|
||||
/** Union params into the existing query, flower-style (see {@link WebApp}). */
|
||||
query(params: Query): WebApp {
|
||||
return new WebApp(unionQuery(this.#url, params), this.#headers, this.#send);
|
||||
return new WebApp(unionQuery(this.#url, params), this.#headers, this.#maps, this.#send);
|
||||
}
|
||||
|
||||
/** Add headers read from `map` at each send, unioned flower-style (see
|
||||
* {@link WebApp}) with the rest — so a contradiction surfaces at send. */
|
||||
withHeaderMap(map: HeaderMap): WebApp {
|
||||
return new WebApp(this.#url, this.#headers, [...this.#maps, map], this.#send);
|
||||
}
|
||||
|
||||
async get(): Promise<string> {
|
||||
return this.#send(this.#url, this.#headers, "GET");
|
||||
return this.#send(this.#url, await this.#headersNow(), "GET");
|
||||
}
|
||||
|
||||
async post(body: string): Promise<string> {
|
||||
return this.#send(this.#url, this.#headers, "POST", body);
|
||||
return this.#send(this.#url, await this.#headersNow(), "POST", body);
|
||||
}
|
||||
|
||||
async #headersNow(): Promise<Headers> {
|
||||
let headers = this.#headers;
|
||||
for (const map of this.#maps) {
|
||||
const entries = await map.entries();
|
||||
for (const [key, value] of entries) {
|
||||
// key name only: header values must not appear in Error messages
|
||||
if (typeof value !== "string") throw new Error(`headers: ${key} is not a string`);
|
||||
}
|
||||
headers = unionHeaders(headers, Object.fromEntries(entries) as Headers);
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -149,6 +180,12 @@ class Gate {
|
||||
* storage, surviving eviction (instance memory evaporates when the DO naps;
|
||||
* storage is where "this instance means this URL" durably lives).
|
||||
*
|
||||
* The cookie is the exception to "fixed at creation": it lives in a store
|
||||
* (`store:cookie:cookie`) rather than in `init`, and every send reads it,
|
||||
* so whoever holds the instance id can rotate it (see {@link cookies})
|
||||
* without a re-mint. Instances minted before that kept it in
|
||||
* `init.headers`; {@link handle} moves it over on first use.
|
||||
*
|
||||
* @see https://developers.cloudflare.com/durable-objects/ — newUniqueId is
|
||||
* unforgeable (128-bit, inderivable); idFromName by contrast is ambient:
|
||||
* any worker with the namespace binding can recompute it
|
||||
@@ -172,11 +209,21 @@ export class WebAppDo extends DurableObject<{ WEBAPP?: never }> {
|
||||
}
|
||||
return; // idempotent for an identical re-configure
|
||||
}
|
||||
await this.ctx.storage.put("init", init);
|
||||
const { cookie, rest } = splitCookie(init.headers ?? {});
|
||||
this.ctx.storage.transactionSync(() => {
|
||||
this.ctx.storage.kv.put("init", { ...init, headers: rest });
|
||||
if (cookie !== undefined) this.cookies().init("cookie", cookie);
|
||||
});
|
||||
})();
|
||||
await this.#ready;
|
||||
}
|
||||
|
||||
/** the instance's cookie, with full authority: `set` rotates it under
|
||||
* every handle already out */
|
||||
cookies(): MapStore<string> {
|
||||
return makeMapStore<string>("cookie", { keyShape: "cookie", valueShape: M.string() }, this.ctx.storage.kv);
|
||||
}
|
||||
|
||||
/** load init from storage; rejects while unconfigured */
|
||||
async #load(): Promise<WebAppInit> {
|
||||
const init = await this.ctx.storage.get<WebAppInit>("init");
|
||||
@@ -189,7 +236,7 @@ export class WebAppDo extends DurableObject<{ WEBAPP?: never }> {
|
||||
/** the fluent stub handed to callers, wired to a fresh gate per
|
||||
* activation (handles within one activation share it) */
|
||||
async handle(): Promise<FluentGet> {
|
||||
const init = await this.#load();
|
||||
const init = this.#migrateCookie(await this.#load());
|
||||
const gate = new Gate(() => sleep(init.msPerCall ?? 0));
|
||||
const send = async (
|
||||
url: string,
|
||||
@@ -207,8 +254,33 @@ export class WebAppDo extends DurableObject<{ WEBAPP?: never }> {
|
||||
}
|
||||
return res.text();
|
||||
};
|
||||
return new WebApp(init.url, init.headers ?? {}, send);
|
||||
return new WebApp(init.url, init.headers ?? {}, [this.cookies().readOnly()], send);
|
||||
}
|
||||
|
||||
/** move a cookie stored in `init.headers` to the cookie store, in one
|
||||
* transaction; returns init without it */
|
||||
#migrateCookie(init: WebAppInit): WebAppInit {
|
||||
const { cookie, rest } = splitCookie(init.headers ?? {});
|
||||
if (cookie === undefined) return init;
|
||||
const migrated = { ...init, headers: rest };
|
||||
this.ctx.storage.transactionSync(() => {
|
||||
const cookies = this.cookies();
|
||||
if (!cookies.has("cookie")) cookies.init("cookie", cookie);
|
||||
this.ctx.storage.kv.put("init", migrated);
|
||||
});
|
||||
return migrated;
|
||||
}
|
||||
}
|
||||
|
||||
/** split the cookie (any case of the header name) from the other headers */
|
||||
function splitCookie(headers: Headers): { cookie?: string; rest: Headers } {
|
||||
const rest: Headers = {};
|
||||
let cookie: string | undefined;
|
||||
for (const [key, value] of Object.entries(headers)) {
|
||||
if (key.toLowerCase() === "cookie") cookie = value;
|
||||
else rest[key] = value;
|
||||
}
|
||||
return { cookie, rest };
|
||||
}
|
||||
|
||||
/** the worker's whole HTTP surface (the default export and the
|
||||
@@ -246,6 +318,13 @@ const defaultFetch = async (
|
||||
return drive(await app, request);
|
||||
}
|
||||
|
||||
// rotate: POST /at/<id>/cookie with JSON {cookie}; the id that drives
|
||||
// an instance can also replace its cookie
|
||||
const rotate = url.pathname.match(/^\/at\/([A-Za-z0-9-]+)\/cookie$/);
|
||||
if (rotate && request.method === "POST") {
|
||||
return rotateCookie(env.WEBAPP_DO.get(env.WEBAPP_DO.idFromString(rotate[1])), request);
|
||||
}
|
||||
|
||||
return new Response("not found", { status: 404 });
|
||||
};
|
||||
|
||||
@@ -368,6 +447,25 @@ async function drive(app: FluentGet, request: Request): Promise<Response> {
|
||||
}
|
||||
}
|
||||
|
||||
/** the /at/<id>/cookie protocol: JSON {cookie} → {ok} (or {error}; no values) */
|
||||
async function rotateCookie(instance: DurableObjectStub<WebAppDo>, request: Request): Promise<Response> {
|
||||
let cookie: unknown;
|
||||
try {
|
||||
({ cookie } = (await request.json()) as { cookie?: unknown });
|
||||
} catch (err) {
|
||||
return Response.json({ error: `bad input: ${String(err)}` }, { status: 400 });
|
||||
}
|
||||
if (typeof cookie !== "string" || !cookie) {
|
||||
return Response.json({ error: "bad input: cookie must be a non-empty string" }, { status: 400 });
|
||||
}
|
||||
using cookies = await instance.cookies();
|
||||
if (await cookies.has("cookie")) await cookies.set("cookie", cookie);
|
||||
else await cookies.init("cookie", cookie);
|
||||
// note: neither id nor cookie logged
|
||||
console.log({ event: "rotate" });
|
||||
return Response.json({ ok: true });
|
||||
}
|
||||
|
||||
function unionHeaders(base: Headers, more: Headers): Headers {
|
||||
const merged = { ...base };
|
||||
for (const [key, value] of Object.entries(more)) {
|
||||
@@ -434,6 +532,13 @@ export class WebAppFactory extends WorkerEntrypoint {
|
||||
const ns = this.env.WEBAPP_DO;
|
||||
return ns.get(ns.idFromString(id)).handle();
|
||||
}
|
||||
|
||||
/** the cookie store of a previously-obtained id: holding the id is
|
||||
* authority to rotate the cookie, not just to use it */
|
||||
async cookies(id: string) {
|
||||
const ns = this.env.WEBAPP_DO;
|
||||
return ns.get(ns.idFromString(id)).cookies();
|
||||
}
|
||||
}
|
||||
function sleep(ms: number): Promise<void> {
|
||||
return new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
Reference in new issue
Block a user