GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(id): worker-poc DO host hardening per Codex review (#2271) · developing-today/code@e68f4cd

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • pkgs/id
    • nix-common.nix
    • worker-poc
      • README.md
      • src
        • guest.ts
        • worker.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎pkgs/id/nix-common.nix‎

Copy file name to clipboardExpand all lines: pkgs/id/nix-common.nix
+1Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,7 @@ let
9494
# Web development tools
9595
bun # JavaScript bundler and runtime (required for web builds)
9696
typescript # TypeScript for type checking # nodepackages remoed 2026-04-03
97+
wrangler # Cloudflare Worker CLI (worker-poc dev, #2271)
9798

9899
# E2E testing (Playwright) — use playwright-driver.browsers for
99100
# pre-patched browser binaries that work with Playwright's CDP protocol.
Collapse file

‎pkgs/id/worker-poc/README.md‎

Copy file name to clipboardExpand all lines: pkgs/id/worker-poc/README.md
+7Lines changed: 7 additions & 0 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,13 @@ evolution only, never on execution-budget behaviour.
4040
snapshot hashes recorded in the run; guest-level cold start (restore
4141
step-2 snapshot, apply `inc`) reproduces the step-3 snapshot hash
4242
`4e07408562…` exactly.
43+
- [x] DO host hardened per Codex review on this PR (2026-11-01): SQLite
44+
BLOB snapshots normalized to Uint8Array before plaza_restore, all
45+
request handling serialized (shared lazy-init promise; update -> hash
46+
-> journal insert is one unit), step inputs validated before any guest
47+
mutation with the guest discarded on journal failure, guest output
48+
pointers normalized unsigned, wrangler declared in nix-common.nix.
49+
Smoke PASS + tsc clean after the fixes.
4350
- [ ] Counter sequence compared against the native reference runner
4451
(native runner over the same scripted sequence via the existing
4552
sandbox/world_fixture machinery — next increment).
Collapse file

‎pkgs/id/worker-poc/src/guest.ts‎

Copy file name to clipboardExpand all lines: pkgs/id/worker-poc/src/guest.ts
+6-2Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,8 +88,12 @@ export class PlazaGuest {
8888
if (len < 0) throw new Error("guest returned a negative output length");
8989
if (len > this.limits.messageBytes) throw new Error(`guest output exceeds ${this.limits.messageBytes} bytes`);
9090
const mem = new Uint8Array(this.ex.memory.buffer);
91-
if (outputPtr + len > mem.length) throw new Error("guest returned output outside linear memory");
92-
return mem.slice(outputPtr, outputPtr + len);
91+
// Normalize the i32 pointer to unsigned before the bounds check and the
92+
// slice, as sandbox.rs does: a negative pointer must fail the bounds
93+
// check, never slice from the end of memory.
94+
const ptr = outputPtr >>> 0;
95+
if (ptr + len > mem.length) throw new Error("guest returned output outside linear memory");
96+
return mem.slice(ptr, ptr + len);
9397
}
9498

9599
update(participant: number, event: Uint8Array): void {
Collapse file

‎pkgs/id/worker-poc/src/worker.ts‎

Copy file name to clipboardExpand all lines: pkgs/id/worker-poc/src/worker.ts
+95-21Lines changed: 95 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,12 @@
1414
// GET /state -> {step, view, records, snapshotHash}
1515
// POST /cold-start -> drops the in-memory guest; the next request lazily
1616
// restores from the journal (this is the forced cold start).
17+
//
18+
// Concurrency: Durable Objects interleave requests at every await, so all
19+
// request handling is serialized through a per-object promise chain. Lazy
20+
// guest initialization is shared through one promise, and a /step runs its
21+
// update -> hash -> journal-insert as one serialized unit, so journal order
22+
// always matches guest evolution order.
1723
import { PlazaGuest } from "./guest.ts";
1824
import { loadHostedModule, type HostedManifest } from "./manifest.ts";
1925
// @ts-expect-error CompiledWasm import: wrangler supplies a WebAssembly.Module.
@@ -40,10 +46,20 @@ async function sha256Hex(bytes: Uint8Array): Promise<string> {
4046
return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
4147
}
4248

49+
// workerd returns SQLite BLOB columns as ArrayBuffer; the Node sqlite driver
50+
// returns Uint8Array. Normalize before handing bytes to the guest.
51+
function asBytes(value: unknown): Uint8Array {
52+
if (value instanceof Uint8Array) return value;
53+
if (value instanceof ArrayBuffer) return new Uint8Array(value);
54+
throw new Error("journal snapshot is not a byte buffer");
55+
}
56+
4357
export class WorldObject {
4458
private sql: SqlStorage;
4559
private guest: PlazaGuest | null = null;
60+
private guestPromise: Promise<PlazaGuest> | null = null;
4661
private step = 0;
62+
private chain: Promise<unknown> = Promise.resolve();
4763

4864
constructor(state: DOState) {
4965
this.sql = state.storage.sql;
@@ -60,51 +76,109 @@ export class WorldObject {
6076
);
6177
}
6278

79+
// Run `fn` after every previously queued request has finished, so awaits
80+
// inside one request can never interleave with another request's work.
81+
private serialized<T>(fn: () => Promise<T>): Promise<T> {
82+
const run = this.chain.then(fn, fn);
83+
this.chain = run.then(
84+
() => undefined,
85+
() => undefined,
86+
);
87+
return run;
88+
}
89+
6390
// Lazy (re)instantiation: fresh init from the seed, or plaza_restore from
6491
// the latest journaled snapshot when the journal is non-empty. This is the
65-
// cold-start path — it runs identically after a real eviction.
66-
private async ensureGuest(): Promise<PlazaGuest> {
67-
if (this.guest) return this.guest;
68-
const rows = this.sql
69-
.exec(`SELECT step, snapshot FROM journal ORDER BY step DESC LIMIT 1`)
70-
.toArray();
71-
const guest = await loadHostedModule(MANIFEST, COUNTER_WASM as WebAssembly.Module, SEED);
72-
if (rows.length > 0) {
73-
guest.restore(rows[0].snapshot as Uint8Array);
74-
this.step = rows[0].step as number;
92+
// cold-start path — it runs identically after a real eviction. Concurrent
93+
// callers share the one in-flight promise, so a guest is never built twice.
94+
private ensureGuest(): Promise<PlazaGuest> {
95+
if (this.guest) return Promise.resolve(this.guest);
96+
if (!this.guestPromise) {
97+
this.guestPromise = (async () => {
98+
const rows = this.sql
99+
.exec(`SELECT step, snapshot FROM journal ORDER BY step DESC LIMIT 1`)
100+
.toArray();
101+
const guest = await loadHostedModule(MANIFEST, COUNTER_WASM as WebAssembly.Module, SEED);
102+
if (rows.length > 0) {
103+
guest.restore(asBytes(rows[0].snapshot));
104+
this.step = rows[0].step as number;
105+
}
106+
this.guest = guest;
107+
return guest;
108+
})();
109+
// A failed initialization must not poison later requests.
110+
this.guestPromise.catch(() => {
111+
this.guestPromise = null;
112+
});
75113
}
76-
this.guest = guest;
77-
return guest;
114+
return this.guestPromise;
115+
}
116+
117+
private dropGuest(): void {
118+
this.guest = null;
119+
this.guestPromise = null;
78120
}
79121

80122
async fetch(req: Request): Promise<Response> {
123+
return this.serialized(() => this.handle(req));
124+
}
125+
126+
private async handle(req: Request): Promise<Response> {
81127
const url = new URL(req.url);
82128
if (req.method === "POST" && url.pathname === "/cold-start") {
83-
this.guest = null; // force the next request through ensureGuest()'s restore path
129+
this.dropGuest(); // force the next request through ensureGuest()'s restore path
84130
return Response.json({ cold: true, journaledStep: this.step });
85131
}
86-
const guest = await this.ensureGuest();
87132
if (req.method === "POST" && url.pathname === "/step") {
88-
const { participant, event } = (await req.json()) as { participant: number; event: string };
133+
// Validate before touching the guest: a malformed request must never
134+
// mutate state it cannot journal.
135+
const body = (await req.json().catch(() => null)) as
136+
| { participant?: unknown; event?: unknown }
137+
| null;
138+
const participant = body?.participant;
139+
const event = body?.event;
140+
if (
141+
typeof participant !== "number" ||
142+
!Number.isInteger(participant) ||
143+
participant < 0 ||
144+
typeof event !== "string" ||
145+
event.length === 0
146+
) {
147+
return Response.json(
148+
{ error: "step requires a non-negative integer participant and a non-empty string event" },
149+
{ status: 400 },
150+
);
151+
}
152+
const guest = await this.ensureGuest();
89153
guest.update(participant, enc.encode(event));
90154
const view = guest.view();
91155
const records = guest.records();
92156
const snapshot = guest.snapshot();
93157
if (!snapshot) throw new Error("guest exports no snapshot; journaling requires the snapshot/restore pair");
94158
const snapshotHash = await sha256Hex(snapshot);
95-
this.step += 1;
96-
this.sql.exec(
97-
`INSERT INTO journal (step, participant, event, snapshot, view, records, snapshot_hash) VALUES (?, ?, ?, ?, ?, ?, ?)`,
98-
this.step, participant, event, snapshot, dec.decode(view),
99-
records ? dec.decode(records) : null, snapshotHash,
100-
);
159+
const nextStep = this.step + 1;
160+
try {
161+
this.sql.exec(
162+
`INSERT INTO journal (step, participant, event, snapshot, view, records, snapshot_hash) VALUES (?, ?, ?, ?, ?, ?, ?)`,
163+
nextStep, participant, event, snapshot, dec.decode(view),
164+
records ? dec.decode(records) : null, snapshotHash,
165+
);
166+
} catch (err) {
167+
// The guest advanced but nothing was journaled: discard it, so the
168+
// next request restores from the journal and the unjournaled event
169+
// cannot contaminate later snapshots.
170+
this.dropGuest();
171+
throw err;
172+
}
173+
this.step = nextStep;
101174
return Response.json({
102175
step: this.step,
103176
view: dec.decode(view),
104177
records: records ? dec.decode(records) : null,
105178
snapshotHash,
106179
});
107180
}
181+
const guest = await this.ensureGuest();
108182
if (req.method === "GET" && url.pathname === "/state") {
109183
const view = guest.view();
110184
const records = guest.records();

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.