neurastream 0.3.20 → 0.3.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/package.json +1 -1
  2. package/src/adapters/index.ts +3 -2
  3. package/src/adapters/omp/adapter.ts +2 -1
  4. package/src/adapters/omp/auto-close.ts +64 -0
  5. package/src/adapters/omp/chat-commands.ts +161 -0
  6. package/src/adapters/omp/inbox.ts +221 -0
  7. package/src/adapters/omp/index.ts +115 -1039
  8. package/src/adapters/omp/launch.ts +31 -3
  9. package/src/adapters/omp/rate-limit-controller.ts +196 -0
  10. package/src/adapters/omp/rollover-controller.ts +334 -0
  11. package/src/adapters/omp/types.ts +143 -0
  12. package/src/cli/commands.ts +33 -2
  13. package/src/cli/dispatch.ts +37 -16
  14. package/src/cli/recall.ts +3 -2
  15. package/src/cli/results-build.ts +1 -1
  16. package/src/cli/workspace.ts +13 -2
  17. package/src/core/adapter.ts +16 -0
  18. package/src/core/blockers.ts +326 -30
  19. package/src/core/file-lock.ts +71 -12
  20. package/src/core/guards/plan-edit.ts +338 -0
  21. package/src/core/guards/planner.ts +70 -0
  22. package/src/core/guards/review.ts +391 -0
  23. package/src/core/guards/spawn.ts +699 -0
  24. package/src/core/guards/state.ts +581 -0
  25. package/src/core/guards/stop.ts +235 -0
  26. package/src/core/guards/tool.ts +541 -0
  27. package/src/core/guards.ts +12 -2658
  28. package/src/core/incidents.ts +125 -91
  29. package/src/core/machine-guard.ts +23 -5
  30. package/src/core/main-start.ts +10 -8
  31. package/src/core/owner-topics.ts +2 -13
  32. package/src/core/owner-ui/auth.ts +164 -0
  33. package/src/core/owner-ui/data.ts +437 -0
  34. package/src/core/owner-ui/handlers.ts +250 -0
  35. package/src/core/owner-ui/messages.ts +209 -0
  36. package/src/core/owner-ui/render.ts +714 -0
  37. package/src/core/owner-ui/results.ts +266 -0
  38. package/src/core/owner-ui/server.ts +142 -0
  39. package/src/core/owner-ui.ts +11 -2121
  40. package/src/core/page-notes.ts +25 -0
  41. package/src/core/pages.ts +452 -77
  42. package/src/core/plan-approval.ts +12 -14
  43. package/src/core/queue/lib.ts +88 -39
  44. package/src/core/queue-cancel.ts +21 -17
  45. package/src/core/queue-close.ts +48 -23
  46. package/src/core/secret-redact.ts +65 -14
  47. package/src/core/tailscale.ts +79 -3
  48. package/src/core/team-client.ts +13 -2
  49. package/src/core/uninstall.ts +2 -0
@@ -107,6 +107,31 @@ export function stripPageNotes(html: string): string {
107
107
  return [STYLE_RE, PANEL_RE, APPROVE_RE, ANSWERED_RE, FAB_RE, SCRIPT_RE].reduce((text, re) => text.replace(re, ""), html);
108
108
  }
109
109
 
110
+ /**
111
+ * Strip only the interactive baked chrome (style, notes panel, approve bar, fab, script) while
112
+ * deliberately preserving `#ns-answered`, so sandboxed raw HTML pages keep answered notes visible
113
+ * without duplicating broken interactive controls that now live in the trusted viewer shell.
114
+ */
115
+ export function stripInteractiveChrome(html: string): string {
116
+ return [STYLE_RE, PANEL_RE, APPROVE_RE, FAB_RE, SCRIPT_RE].reduce((text, re) => text.replace(re, ""), html);
117
+ }
118
+
119
+ /**
120
+ * Minimal read-only selection relay appended to sandboxed `/_raw/<name>` HTML responses.
121
+ * Relays selected text to the trusted parent viewer shell via `postMessage`; guarded so stubbed
122
+ * DOM environments where `window.parent` is undefined never throw.
123
+ */
124
+ export const QUOTE_RELAY_SCRIPT = `<script>(function(){
125
+ function relay(){
126
+ if(!window.parent||window.parent===window)return;
127
+ var s=window.getSelection?window.getSelection():null;
128
+ var q=s?s.toString().replace(/\\s+/g," ").trim().slice(0,600):"";
129
+ if(q)window.parent.postMessage({type:"ns-quote",quote:q},"*");
130
+ }
131
+ document.addEventListener("mouseup",relay);
132
+ document.addEventListener("selectionchange",relay);
133
+ })();</script>`;
134
+
110
135
  /** What the Approve bar needs: the page it approves, the notes still open on it and what the
111
136
  * diagram check found (P9, P10). */
112
137
  export interface ApproveChrome {
package/src/core/pages.ts CHANGED
@@ -1,86 +1,461 @@
1
+ import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
1
2
  import { appendFileSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync } from "node:fs";
2
3
  import { basename, extname, resolve } from "node:path";
3
- import type { Config } from "./config.ts";
4
- import { isLoopback, isTailnet, inboxPath, type UiHttpServer } from "./owner-ui.ts";
5
- import { nowSec } from "./clock.ts";
6
- import { appendPageNotes, openNoteIds } from "./page-notes.ts";
7
- import { approvePlanFile, readPagePlan } from "./plan-approval.ts";
8
4
  import type { RunSource } from "./adapter.ts";
5
+ import { nowSec } from "./clock.ts";
6
+ import type { Config } from "./config.ts";
7
+ import { authenticate, hostAllowlist, inboxPath, originIsHost, type UiHttpServer } from "./owner-ui.ts";
8
+ import { appendPageNotes, openNoteIds, QUOTE_RELAY_SCRIPT, stripInteractiveChrome } from "./page-notes.ts";
9
+ import { approvePlanFile, readPagePlan, type PagePlan } from "./plan-approval.ts";
9
10
  import type { Tailscale } from "./tailscale.ts";
10
11
 
11
- export interface PagesServer { stop(): void; hostname: string; port: number }
12
- export interface PagesOptions { cfg: Config; tailscale: Tailscale; source: RunSource; hostname?: string; port?: number; peerOf?: (req: Request, server: UiHttpServer) => string; root?: string }
13
- const MIME: Record<string, string> = { ".html":"text/html; charset=utf-8", ".css":"text/css; charset=utf-8", ".js":"text/javascript; charset=utf-8", ".mjs":"text/javascript; charset=utf-8", ".svg":"image/svg+xml", ".png":"image/png", ".jpg":"image/jpeg", ".jpeg":"image/jpeg", ".webp":"image/webp", ".json":"application/json", ".txt":"text/plain; charset=utf-8", ".ico":"image/x-icon", ".woff2":"font/woff2", ".map":"application/json" };
14
- function urlPart(value: string): string { return encodeURI(value).replaceAll("?", "%3F").replaceAll("#", "%23").replaceAll('"', "%22").replaceAll("'", "%27"); }
15
- function plain(body: string, status: number): Response { return new Response(body, { status, headers: { "content-type":"text/plain; charset=utf-8" } }); }
16
- export function startPagesServer(opts: PagesOptions): PagesServer {
17
- const hostname = opts.hostname ?? opts.tailscale.ip4();
18
- if (!hostname) throw new Error("pages: tailscale ip -4 did not answer");
19
- const root = resolve(opts.root ?? opts.cfg.pages.dir);
20
- const peerOf = opts.peerOf ?? ((req: Request, server: UiHttpServer) => server.requestIP(req)?.address ?? "");
21
- const server = Bun.serve({ hostname, port: opts.port ?? opts.cfg.pages.port, async fetch(req, srv) {
22
- if (req.method !== "GET" && req.method !== "HEAD" && req.method !== "POST") return plain("method not allowed", 405);
23
- const peer = peerOf(req, srv);
24
- const login = isLoopback(peer) ? null : isTailnet(peer) ? opts.tailscale.whois(peer) : null;
25
- if (!isLoopback(peer) && (!login || login !== opts.cfg.workspace.owner_login)) return plain("forbidden", 403);
26
- const url = new URL(req.url);
27
- // The one POST a page may make (plan 20261026 P6): the notes its script collected become owner-inbox
28
- // rows Main delivers. Same origin only, so another site's tab cannot write to the inbox; nothing here
29
- // touches the page file, and a submit with no note text is refused.
30
- if (req.method === "POST") {
31
- // Approve from the plan's own page (plan 20261026 P9): the click records a hash of the plan text
32
- // in the queue state (plan-approvals.json). Only that plan, only from this page's origin, and
33
- // never while a note on the page has no answer.
34
- if (url.pathname === "/_approve") {
35
- if (req.headers.get("origin") !== `http://${req.headers.get("host")}`) return plain("forbidden: origin is not this page", 403);
36
- const page = url.searchParams.get("page") ?? "";
37
- const record = page === "" ? null : readPagePlan(root, page);
38
- if (record === null) return plain("not found: no plan is published as this page", 404);
39
- const open = openNoteIds(opts.cfg, page);
40
- if (open.length > 0) return Response.json({ error: `answer ${open.join(", ")} first` }, { status: 409 });
41
- const unproven = [...record.missing, ...record.thin];
42
- if (unproven.length > 0) return Response.json({ error: `the diagram is not complete (${unproven.slice(0, 3).join("; ")})` }, { status: 409 });
43
- const plan = record.plan;
44
- if (!existsSync(plan)) return plain("not found: the plan file is gone", 404);
45
- try {
46
- const approved = approvePlanFile(plan, page, opts.cfg.paths);
47
- // P5 (plan 20261031_0917): the tap must reach Main at once — one owner-inbox row, the same
48
- // direct append the message POST uses; never a page note, which would 409 the next tap.
49
- mkdirSync(opts.cfg.paths.queue_state, { recursive: true });
50
- appendFileSync(inboxPath(opts.cfg.paths), `${JSON.stringify({ ts: nowSec(), kind: "approval", page, plan, login })}\n`);
51
- return Response.json({ approved });
52
- } catch (e) {
53
- return plain(`not approved: ${e instanceof Error ? e.message : String(e)}`, 500);
54
- }
12
+ export interface PagesServer {
13
+ stop(): void;
14
+ hostname: string;
15
+ port: number;
16
+ }
17
+
18
+ export interface PagesOptions {
19
+ cfg: Config;
20
+ tailscale: Tailscale;
21
+ source: RunSource;
22
+ hostname?: string;
23
+ port?: number;
24
+ peerOf?: (req: Request, server: UiHttpServer) => string;
25
+ root?: string;
26
+ }
27
+
28
+ const MIME: Record<string, string> = {
29
+ ".html": "text/html; charset=utf-8",
30
+ ".css": "text/css; charset=utf-8",
31
+ ".js": "text/javascript; charset=utf-8",
32
+ ".mjs": "text/javascript; charset=utf-8",
33
+ ".svg": "image/svg+xml",
34
+ ".png": "image/png",
35
+ ".jpg": "image/jpeg",
36
+ ".jpeg": "image/jpeg",
37
+ ".webp": "image/webp",
38
+ ".json": "application/json",
39
+ ".txt": "text/plain; charset=utf-8",
40
+ ".ico": "image/x-icon",
41
+ ".woff2": "font/woff2",
42
+ ".map": "application/json",
43
+ };
44
+
45
+ /** Escape HTML special characters for safe interpolation into text or attributes. */
46
+ function esc(text: string): string {
47
+ return text
48
+ .replaceAll("&", "&amp;")
49
+ .replaceAll("<", "&lt;")
50
+ .replaceAll(">", "&gt;")
51
+ .replaceAll('"', "&quot;")
52
+ .replaceAll("'", "&#39;");
53
+ }
54
+
55
+ /** Percent-encode a filename for safe inclusion in URL paths and Content-Disposition headers. */
56
+ function urlPart(value: string): string {
57
+ return encodeURI(value)
58
+ .replaceAll("?", "%3F")
59
+ .replaceAll("#", "%23")
60
+ .replaceAll('"', "%22")
61
+ .replaceAll("'", "%27");
62
+ }
63
+
64
+ /** Return a plain-text response with `X-Content-Type-Options: nosniff`. */
65
+ function plain(body: string, status: number): Response {
66
+ return new Response(body, {
67
+ status,
68
+ headers: {
69
+ "content-type": "text/plain; charset=utf-8",
70
+ "x-content-type-options": "nosniff",
71
+ },
72
+ });
73
+ }
74
+
75
+ /** Return a JSON response with `X-Content-Type-Options: nosniff`. */
76
+ function json(data: unknown, status = 200): Response {
77
+ return Response.json(data, {
78
+ status,
79
+ headers: { "x-content-type-options": "nosniff" },
80
+ });
81
+ }
82
+
83
+ /**
84
+ * Normalize a page name or path to its canonical filename so viewer-shell token minting and
85
+ * POST verification agree across `/why.html`, `why.html`, `/`, and `index.html`.
86
+ */
87
+ export function normalizePageName(raw: string): string {
88
+ const stripped = raw.replace(/^\/+/, "");
89
+ return stripped === "" ? "index.html" : stripped;
90
+ }
91
+
92
+ /** Sign an HMAC-SHA256 action token bound to a specific action and normalized page name. */
93
+ function signActionToken(secret: Buffer, action: "approve" | "notes", page: string): string {
94
+ return createHmac("sha256", secret).update(`${action}\0${normalizePageName(page)}`).digest("hex");
95
+ }
96
+
97
+ /** Verify an HMAC-SHA256 action token in constant time for the given action and page name. */
98
+ function verifyActionToken(secret: Buffer, action: "approve" | "notes", page: string, token: string | null): boolean {
99
+ if (!token || !/^[0-9a-f]{64}$/i.test(token)) return false;
100
+ const expected = Buffer.from(signActionToken(secret, action, page), "hex");
101
+ const received = Buffer.from(token, "hex");
102
+ return expected.length === received.length && timingSafeEqual(expected, received);
103
+ }
104
+
105
+ type ResolvedStatic =
106
+ | { ok: true; name: string; path: string }
107
+ | { ok: false; status: 400 | 404; message: string };
108
+
109
+ /**
110
+ * Safely decode and resolve a flat filename under `root`.
111
+ * Catches malformed percent-encoding (400) and rejects traversal, hidden files, and symlinks (404).
112
+ */
113
+ function resolveStaticFile(root: string, rawSegment: string): ResolvedStatic {
114
+ let name: string;
115
+ try {
116
+ name = decodeURI(rawSegment);
117
+ } catch {
118
+ return { ok: false, status: 400, message: "bad request" };
119
+ }
120
+ if (!name || name.includes("/") || name.includes("\\") || name === ".." || name.startsWith(".") || name.includes("\0")) {
121
+ return { ok: false, status: 404, message: "not found" };
122
+ }
123
+ const path = resolve(root, name);
124
+ if (basename(path) !== name || !existsSync(path) || !lstatSync(path).isFile()) {
125
+ return { ok: false, status: 404, message: "not found" };
126
+ }
127
+ return { ok: true, name, path };
128
+ }
129
+
130
+ /** Insert a block just before the final `</body>` tag, or append it if no closing body tag exists. */
131
+ function appendBeforeBodyClose(html: string, block: string): string {
132
+ const at = html.toLowerCase().lastIndexOf("</body>");
133
+ return at < 0 ? `${html}\n${block}\n` : `${html.slice(0, at)}${block}\n${html.slice(at)}`;
134
+ }
135
+
136
+ // Static viewer-shell client script: reads page name and action tokens from DOM data attributes
137
+ // so zero untrusted input is ever interpolated into JavaScript source.
138
+ const VIEWER_SHELL_SCRIPT = `(function(){
139
+ var frame=document.getElementById("ns-frame");
140
+ var panel=document.getElementById("ns-notes");
141
+ var list=document.getElementById("ns-list");
142
+ var fab=document.getElementById("ns-note-fab");
143
+ var status=document.getElementById("ns-status");
144
+ var addBtn=document.getElementById("ns-add");
145
+ var pageName=panel?panel.dataset.nsPage||"":"";
146
+ var notesToken=panel?panel.dataset.nsToken||"":"";
147
+ var notes=[];
148
+ function paint(){
149
+ list.textContent="";
150
+ notes.forEach(function(n,at){
151
+ var row=document.createElement("div");row.className="ns-row";
152
+ if(n.quote){var q=document.createElement("p");q.className="ns-quote";q.textContent="\\u201c"+n.quote+"\\u201d";row.appendChild(q);}
153
+ var ta=document.createElement("textarea");ta.value=n.note;ta.placeholder="What about this passage?";
154
+ ta.addEventListener("input",function(){notes[at].note=ta.value;notes[at].relayed=false;});
155
+ var del=document.createElement("button");del.className="ns-quiet";del.type="button";del.textContent="Remove";
156
+ del.addEventListener("click",function(){notes.splice(at,1);paint();});
157
+ row.appendChild(ta);row.appendChild(del);list.appendChild(row);
158
+ });
159
+ panel.hidden=notes.length===0;
160
+ }
161
+ function addRow(quote,relayed){
162
+ if(relayed){
163
+ for(var i=notes.length-1;i>=0;i--){
164
+ if(notes[i].relayed&&notes[i].note===""){notes[i].quote=quote;paint();return;}
55
165
  }
56
- if (url.pathname !== "/_notes") return plain("method not allowed", 405);
57
- if (req.headers.get("origin") !== `http://${req.headers.get("host")}`) return plain("forbidden: origin is not this page", 403);
58
- let body: unknown; try { body = await req.json(); } catch { return plain("bad request: not JSON", 400); }
59
- const stored = appendPageNotes(body, opts.cfg, login ?? "loopback");
60
- return stored === null ? plain("no notes to submit", 400) : Response.json({ stored });
61
- }
62
- // What the Approve bar asks on load: the notes still open on this page. A page with no plan has none.
63
- if (url.pathname === "/_approve") {
64
- const page = url.searchParams.get("page") ?? "";
65
- const record = page === "" ? null : readPagePlan(root, page);
66
- if (record === null) return plain("not found: no plan is published as this page", 404);
67
- return Response.json({ open: openNoteIds(opts.cfg, page), problems: [...record.missing, ...record.thin] });
68
166
  }
69
- let name = decodeURI(url.pathname.slice(1));
70
- if (name.includes("/") || name.includes("\\") || name === ".." || name.startsWith(".")) return plain("not found", 404);
71
- if (!name) {
72
- const index = resolve(root, "index.html");
73
- if (existsSync(index) && lstatSync(index).isFile()) name = "index.html";
74
- else {
75
- const files = existsSync(root) ? readdirSync(root, { withFileTypes:true }).filter(e => !e.name.startsWith(".") && e.isFile()).map(e => e.name) : [];
76
- const body = `<!doctype html><ul>${files.map(f => `<li><a href="/${urlPart(f)}">${f.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}</a></li>`).join("")}</ul>`;
77
- return new Response(req.method === "HEAD" ? null : body, { headers:{ "content-type":"text/html; charset=utf-8" } });
78
- }
167
+ notes.push({quote:quote,note:"",relayed:Boolean(relayed)});
168
+ paint();
169
+ var boxes=list.querySelectorAll("textarea");
170
+ if(boxes.length)boxes[boxes.length-1].focus();
171
+ }
172
+ window.addEventListener("message",function(ev){
173
+ if(!frame||ev.source!==frame.contentWindow||ev.origin!=="null")return;
174
+ var d=ev.data;
175
+ if(!d||typeof d!=="object"||d.type!=="ns-quote"||typeof d.quote!=="string")return;
176
+ var q=d.quote.replace(/\\s+/g," ").trim().slice(0,600);
177
+ if(!q)return;
178
+ addRow(q,true);
179
+ });
180
+ if(fab)fab.addEventListener("click",function(){addRow("",false);});
181
+ if(addBtn)addBtn.addEventListener("click",function(){addRow("",false);});
182
+ var hideBtn=document.getElementById("ns-hide");
183
+ if(hideBtn)hideBtn.addEventListener("click",function(){panel.hidden=true;});
184
+ var submitBtn=document.getElementById("ns-submit");
185
+ if(submitBtn)submitBtn.addEventListener("click",function(){
186
+ var keep=notes.filter(function(n){return n.note.trim()!=="";}).map(function(n){return {quote:n.quote,note:n.note};});
187
+ if(keep.length===0){status.textContent="write a note first";return;}
188
+ status.textContent="sending\\u2026";
189
+ fetch("/_notes",{method:"POST",headers:{"content-type":"application/json","x-ns-token":notesToken},body:JSON.stringify({page:"/"+pageName,url:location.href,notes:keep})})
190
+ .then(function(r){if(!r.ok)throw new Error(r.status);return r.json();})
191
+ .then(function(j){notes=[];paint();status.textContent="sent "+j.stored+" note(s)";})
192
+ .catch(function(){status.textContent="not sent \\u2014 try again";});
193
+ });
194
+ var approveSec=document.getElementById("ns-approve");
195
+ if(approveSec){
196
+ var approvePage=approveSec.dataset.nsPlan||"";
197
+ var approveToken=approveSec.dataset.nsToken||"";
198
+ var btn=document.getElementById("ns-approve-btn");
199
+ var astatus=document.getElementById("ns-approve-status");
200
+ function setApprove(open,problems){
201
+ var bad=problems||[];
202
+ btn.disabled=open.length>0||bad.length>0;
203
+ astatus.textContent=open.length>0?"Answer every note first ("+open.join(", ")+")":bad.length>0?"The diagram is not complete yet ("+bad.length+"): "+bad.slice(0,3).join("; "):"Approve and go \\u2014 the plan records it.";
79
204
  }
80
- const path = resolve(root, name);
81
- if (basename(path) !== name || !existsSync(path) || !lstatSync(path).isFile()) return plain("not found", 404);
82
- const type = MIME[extname(name).toLowerCase()] ?? "application/octet-stream";
83
- return new Response(req.method === "HEAD" ? null : readFileSync(path), { headers:{ "content-type":type, ...(type === "application/octet-stream" ? { "content-disposition":`attachment; filename*=UTF-8''${urlPart(name)}` } : {}) } });
84
- }});
85
- return { stop: () => server.stop(true), hostname, port: Number(server.port) };
205
+ fetch("/_approve?page="+encodeURIComponent(approvePage))
206
+ .then(function(r){return r.json();})
207
+ .then(function(d){setApprove(d.open||[],d.problems);})
208
+ .catch(function(){setApprove(["?"],[]);});
209
+ btn.addEventListener("click",function(){
210
+ btn.disabled=true;
211
+ fetch("/_approve?page="+encodeURIComponent(approvePage),{method:"POST",headers:{"content-type":"application/json","x-ns-token":approveToken},body:"{}"})
212
+ .then(function(r){return r.json().then(function(d){return {ok:r.ok,body:d};});})
213
+ .then(function(res){astatus.textContent=res.ok?res.body.approved:"Not approved: "+res.body.error;btn.disabled=!res.ok;})
214
+ .catch(function(){astatus.textContent="Not approved: the pages server did not answer.";btn.disabled=false;});
215
+ });
216
+ }
217
+ })();`;
218
+
219
+ const VIEWER_SHELL_STYLE = `html,body{margin:0;padding:0;width:100%;height:100%;overflow:hidden;background:#f6f7f9}
220
+ #ns-frame{position:fixed;inset:0;width:100%;height:100%;border:0}
221
+ #ns-notes{position:fixed;inset-block-end:0;inset-inline-end:0;z-index:2147483000;width:min(420px,100vw);max-height:60vh;overflow:auto;font:13px/1.4 system-ui,sans-serif;background:#111c;color:#fff;backdrop-filter:blur(6px);border-start-start-radius:10px;padding:10px;box-sizing:border-box}
222
+ #ns-notes h2{margin:0 0 6px;font-size:13px;font-weight:600;opacity:.8}
223
+ #ns-notes .ns-row{border-top:1px solid #fff3;padding:6px 0}
224
+ #ns-notes .ns-quote{margin:0 0 4px;opacity:.75;font-style:italic;word-break:break-word}
225
+ #ns-notes textarea{width:100%;box-sizing:border-box;min-height:38px;font:inherit;color:#000;border-radius:6px;border:0;padding:6px}
226
+ #ns-notes .ns-actions{display:flex;gap:6px;align-items:center;margin-top:6px;flex-wrap:wrap}
227
+ #ns-notes button{font:inherit;border:0;border-radius:6px;padding:6px 10px;background:#3b82f6;color:#fff}
228
+ #ns-notes button.ns-quiet{background:#fff2;color:#fff}
229
+ #ns-notes .ns-status{opacity:.8}
230
+ #ns-note-fab{position:fixed;inset-block-end:12px;inset-inline-end:12px;z-index:2147482999;font:12px system-ui,sans-serif;border:0;border-radius:6px;padding:6px 10px;background:#3b82f6;color:#fff}
231
+ #ns-approve{position:fixed;inset-block-start:0;inset-inline-end:0;z-index:2147483000;display:flex;gap:8px;align-items:center;padding:8px 10px;font:13px/1.4 system-ui,sans-serif;background:#111c;color:#fff;backdrop-filter:blur(6px);border-end-start-radius:8px}
232
+ #ns-approve button{font:inherit;border:0;border-radius:6px;padding:6px 12px;background:#16a34a;color:#fff}
233
+ #ns-approve button[disabled]{background:#fff3;color:#fff9}`;
234
+
235
+ /** Render the trusted outer viewer shell that iframes `/_raw/<name>` in an opaque sandbox. */
236
+ function renderViewerShell(opts: {
237
+ name: string;
238
+ nonce: string;
239
+ notesToken: string;
240
+ approveToken: string | null;
241
+ planRecord: PagePlan | null;
242
+ openNotes: string[];
243
+ }): string {
244
+ const { name, nonce, notesToken, approveToken, planRecord, openNotes } = opts;
245
+ const safeName = esc(name);
246
+ let approveHtml = "";
247
+ if (planRecord !== null && approveToken !== null) {
248
+ const problems = [...planRecord.missing, ...planRecord.thin];
249
+ const hint =
250
+ openNotes.length > 0
251
+ ? `Answer every note first (${esc(openNotes.join(", "))})`
252
+ : problems.length > 0
253
+ ? `The diagram is not complete yet (${problems.length}): ${esc(problems.slice(0, 3).join("; "))}`
254
+ : "Approve and go";
255
+ const disabled = openNotes.length === 0 && problems.length === 0 ? "" : " disabled";
256
+ approveHtml = `<section id="ns-approve" data-ns-plan="${safeName}" data-ns-token="${approveToken}">
257
+ <button id="ns-approve-btn" type="button"${disabled}>Approve</button><span id="ns-approve-status" class="ns-status">${hint}</span>
258
+ </section>`;
259
+ }
260
+ return `<!doctype html>
261
+ <html lang="en">
262
+ <head>
263
+ <meta charset="utf-8">
264
+ <meta name="viewport" content="width=device-width,initial-scale=1">
265
+ <title>${safeName}</title>
266
+ <style>${VIEWER_SHELL_STYLE}</style>
267
+ </head>
268
+ <body>
269
+ <iframe id="ns-frame" sandbox="allow-scripts" title="${safeName}" src="/_raw/${esc(urlPart(name))}"></iframe>
270
+ ${approveHtml}
271
+ <section id="ns-notes" data-ns-page="${safeName}" data-ns-token="${notesToken}" hidden>
272
+ <h2>Notes on this page</h2>
273
+ <div id="ns-list"></div>
274
+ <div class="ns-actions"><button id="ns-add" class="ns-quiet" type="button">Add note</button><button id="ns-submit" type="button">Submit all</button><button id="ns-hide" class="ns-quiet" type="button">Hide</button><span id="ns-status" class="ns-status"></span></div>
275
+ </section>
276
+ <button id="ns-note-fab" type="button">Add note</button>
277
+ <script nonce="${nonce}">${VIEWER_SHELL_SCRIPT}</script>
278
+ </body>
279
+ </html>`;
280
+ }
281
+
282
+ /**
283
+ * Start the pages HTTP server over Tailscale with owner authentication, DNS-rebinding Host
284
+ * validation, HMAC-SHA256 action tokens, sandboxed raw HTML/SVG isolation, and a trusted
285
+ * viewer shell for Approve and Notes actions.
286
+ */
287
+ export function startPagesServer(opts: PagesOptions): PagesServer {
288
+ const hostname = opts.hostname ?? opts.tailscale.ip4();
289
+ if (!hostname) throw new Error("pages: tailscale ip -4 did not answer");
290
+ const root = resolve(opts.root ?? opts.cfg.pages.dir);
291
+ const peerOf = opts.peerOf ?? ((req: Request, server: UiHttpServer) => server.requestIP(req)?.address ?? "");
292
+ const hostAllowed = hostAllowlist(opts.tailscale, { allowLoopback: opts.cfg.workspace.allow_this_machine });
293
+ const secret = randomBytes(32);
294
+
295
+ const server = Bun.serve({
296
+ hostname,
297
+ port: opts.port ?? opts.cfg.pages.port,
298
+ async fetch(req, srv) {
299
+ const hostHeader = req.headers.get("host") ?? "";
300
+ if (!hostAllowed(hostHeader, srv.port)) return plain("forbidden: host is not this page", 403);
301
+
302
+ const auth = authenticate(opts.cfg, opts.tailscale, peerOf(req, srv));
303
+ if (!auth.ok) return plain("forbidden", 403);
304
+
305
+ if (req.method !== "GET" && req.method !== "HEAD" && req.method !== "POST") {
306
+ return plain("method not allowed", 405);
307
+ }
308
+
309
+ const url = new URL(req.url);
310
+
311
+ // Privileged write routes: require same-origin AND a valid per-page HMAC-SHA256 action token.
312
+ if (req.method === "POST") {
313
+ if (url.pathname === "/_approve") {
314
+ if (!originIsHost(req.headers.get("origin"), hostHeader)) {
315
+ return plain("forbidden: origin is not this page", 403);
316
+ }
317
+ const rawPage = url.searchParams.get("page") ?? "";
318
+ const page = rawPage === "" ? "" : normalizePageName(rawPage);
319
+ if (page === "" || !verifyActionToken(secret, "approve", page, req.headers.get("x-ns-token"))) {
320
+ return plain("forbidden: invalid action token", 403);
321
+ }
322
+ const record = readPagePlan(root, page);
323
+ if (record === null) return plain("not found: no plan is published as this page", 404);
324
+ const open = openNoteIds(opts.cfg, page);
325
+ if (open.length > 0) return json({ error: `answer ${open.join(", ")} first` }, 409);
326
+ const unproven = [...record.missing, ...record.thin];
327
+ if (unproven.length > 0) {
328
+ return json({ error: `the diagram is not complete (${unproven.slice(0, 3).join("; ")})` }, 409);
329
+ }
330
+ const plan = record.plan;
331
+ if (!existsSync(plan)) return plain("not found: the plan file is gone", 404);
332
+ try {
333
+ const approved = approvePlanFile(plan, page, opts.cfg.paths);
334
+ // P5 (plan 20261031_0917): the tap must reach Main at once — one owner-inbox row, the same
335
+ // direct append the message POST uses; never a page note, which would 409 the next tap.
336
+ mkdirSync(opts.cfg.paths.queue_state, { recursive: true });
337
+ appendFileSync(
338
+ inboxPath(opts.cfg.paths),
339
+ `${JSON.stringify({ ts: nowSec(), kind: "approval", page, plan, login: auth.login })}\n`,
340
+ );
341
+ return json({ approved });
342
+ } catch (e) {
343
+ return plain(`not approved: ${e instanceof Error ? e.message : String(e)}`, 500);
344
+ }
345
+ }
346
+
347
+ if (url.pathname === "/_notes") {
348
+ if (!originIsHost(req.headers.get("origin"), hostHeader)) {
349
+ return plain("forbidden: origin is not this page", 403);
350
+ }
351
+ let body: unknown;
352
+ try {
353
+ body = await req.json();
354
+ } catch {
355
+ return plain("bad request: not JSON", 400);
356
+ }
357
+ const bodyPage =
358
+ body !== null && typeof body === "object" && !Array.isArray(body) && typeof (body as Record<string, unknown>).page === "string"
359
+ ? ((body as Record<string, unknown>).page as string)
360
+ : "";
361
+ if (!verifyActionToken(secret, "notes", bodyPage, req.headers.get("x-ns-token"))) {
362
+ return plain("forbidden: invalid action token", 403);
363
+ }
364
+ const stored = appendPageNotes(body, opts.cfg, auth.login);
365
+ return stored === null ? plain("no notes to submit", 400) : json({ stored });
366
+ }
367
+
368
+ return plain("method not allowed", 405);
369
+ }
370
+
371
+ // What the Approve bar asks on load: the notes still open on this page. A page with no plan has none.
372
+ if (url.pathname === "/_approve") {
373
+ const rawPage = url.searchParams.get("page") ?? "";
374
+ const page = rawPage === "" ? "" : normalizePageName(rawPage);
375
+ const record = page === "" ? null : readPagePlan(root, page);
376
+ if (record === null) return plain("not found: no plan is published as this page", 404);
377
+ return json({ open: openNoteIds(opts.cfg, page), problems: [...record.missing, ...record.thin] });
378
+ }
379
+
380
+ // Sandboxed raw HTML content served into the viewer shell's opaque-origin iframe.
381
+ if (url.pathname.startsWith("/_raw/")) {
382
+ const resolved = resolveStaticFile(root, url.pathname.slice("/_raw/".length));
383
+ if (!resolved.ok) return plain(resolved.message, resolved.status);
384
+ if (extname(resolved.name).toLowerCase() !== ".html") return plain("not found", 404);
385
+ const headers = {
386
+ "content-type": "text/html; charset=utf-8",
387
+ "content-security-policy": "sandbox allow-scripts",
388
+ "x-content-type-options": "nosniff",
389
+ };
390
+ if (req.method === "HEAD") return new Response(null, { headers });
391
+ const rawHtml = readFileSync(resolved.path, "utf8");
392
+ const body = appendBeforeBodyClose(stripInteractiveChrome(rawHtml), QUOTE_RELAY_SCRIPT);
393
+ return new Response(body, { headers });
394
+ }
395
+
396
+ // Root path: serve index.html via the trusted viewer shell if present, else a file index.
397
+ let resolved: ResolvedStatic;
398
+ if (url.pathname === "/") {
399
+ const indexPath = resolve(root, "index.html");
400
+ if (existsSync(indexPath) && lstatSync(indexPath).isFile()) {
401
+ resolved = { ok: true, name: "index.html", path: indexPath };
402
+ } else {
403
+ const files = existsSync(root)
404
+ ? readdirSync(root, { withFileTypes: true })
405
+ .filter(e => !e.name.startsWith(".") && e.isFile())
406
+ .map(e => e.name)
407
+ : [];
408
+ const body = `<!doctype html><ul>${files.map(f => `<li><a href="/${esc(urlPart(f))}">${esc(f)}</a></li>`).join("")}</ul>`;
409
+ return new Response(req.method === "HEAD" ? null : body, {
410
+ headers: {
411
+ "content-type": "text/html; charset=utf-8",
412
+ "content-security-policy": "default-src 'none'; base-uri 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'",
413
+ "x-content-type-options": "nosniff",
414
+ },
415
+ });
416
+ }
417
+ } else {
418
+ resolved = resolveStaticFile(root, url.pathname.slice(1));
419
+ if (!resolved.ok) return plain(resolved.message, resolved.status);
420
+ }
421
+
422
+ const ext = extname(resolved.name).toLowerCase();
423
+ if (ext === ".html") {
424
+ const nonce = randomBytes(16).toString("base64");
425
+ const planRecord = readPagePlan(root, resolved.name);
426
+ const notesToken = signActionToken(secret, "notes", resolved.name);
427
+ const approveToken = planRecord === null ? null : signActionToken(secret, "approve", resolved.name);
428
+ const headers = {
429
+ "content-type": "text/html; charset=utf-8",
430
+ "content-security-policy": `default-src 'none'; base-uri 'none'; script-src 'nonce-${nonce}'; style-src 'unsafe-inline'; frame-src 'self'; connect-src 'self'; frame-ancestors 'none'`,
431
+ "x-content-type-options": "nosniff",
432
+ };
433
+ if (req.method === "HEAD") return new Response(null, { headers });
434
+ const body = renderViewerShell({
435
+ name: resolved.name,
436
+ nonce,
437
+ notesToken,
438
+ approveToken,
439
+ planRecord,
440
+ openNotes: planRecord === null ? [] : openNoteIds(opts.cfg, resolved.name),
441
+ });
442
+ return new Response(body, { headers });
443
+ }
444
+
445
+ const type = MIME[ext] ?? "application/octet-stream";
446
+ const headers: Record<string, string> = {
447
+ "content-type": type,
448
+ "x-content-type-options": "nosniff",
449
+ };
450
+ if (type === "image/svg+xml") {
451
+ headers["content-security-policy"] = "sandbox";
452
+ }
453
+ if (type === "application/octet-stream") {
454
+ headers["content-disposition"] = `attachment; filename*=UTF-8''${urlPart(resolved.name)}`;
455
+ }
456
+ return new Response(req.method === "HEAD" ? null : readFileSync(resolved.path), { headers });
457
+ },
458
+ });
459
+
460
+ return { stop: () => server.stop(true), hostname, port: Number(server.port) };
86
461
  }
@@ -4,6 +4,7 @@
4
4
  // has no record with the plan's current hash; a plan with no page predates the convention and is left alone, unless it is stamped at or after approval.since (plan 20261029_1455 P3), when it is refused until its page is published.
5
5
  import { appendFileSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
6
6
  import { basename, join, resolve } from "node:path";
7
+ import { withFileLock, writeAtomicSync } from "./file-lock.ts";
7
8
  import * as q from "./queue/lib.ts";
8
9
  import type { Config } from "./config.ts";
9
10
 
@@ -96,25 +97,22 @@ function readPlanApprovals(paths: Pick<q.QueuePaths, "queue_state">): Record<str
96
97
  return {};
97
98
  }
98
99
 
99
- function writePlanApprovals(approvals: Record<string, PlanApproval>, paths: Pick<q.QueuePaths, "queue_state">): boolean {
100
- try {
101
- mkdirSync(paths.queue_state, { recursive: true });
102
- writeFileSync(planApprovalsFile(paths), JSON.stringify({ approvals }, null, 1));
103
- return true;
104
- } catch {
105
- return false;
106
- }
107
- }
108
-
109
100
  function readPlanApproval(file: string, paths: Pick<q.QueuePaths, "queue_state">): PlanApproval | null {
110
101
  return readPlanApprovals(paths)[file] ?? null;
111
102
  }
112
103
 
113
- /** Record one approval. Throws when the queue state cannot be written, so nobody reports "approved" for a record that is not there. */
104
+ /** Record one approval atomically under lock. Throws when the queue state cannot be written, so nobody reports "approved" for a record that is not there. */
114
105
  function recordApproval(file: string, approval: PlanApproval, paths: Pick<q.QueuePaths, "queue_state">): void {
115
- const approvals = readPlanApprovals(paths);
116
- approvals[file] = approval;
117
- if (!writePlanApprovals(approvals, paths)) throw new Error(`cannot write ${planApprovalsFile(paths)}`);
106
+ const target = planApprovalsFile(paths);
107
+ try {
108
+ withFileLock(`${target}.lock`, () => {
109
+ const approvals = readPlanApprovals(paths);
110
+ approvals[file] = approval;
111
+ writeAtomicSync(target, JSON.stringify({ approvals }, null, 1));
112
+ });
113
+ } catch {
114
+ throw new Error(`cannot write ${target}`);
115
+ }
118
116
  }
119
117
 
120
118
  /** The owner's click on a plan page: record a hash of the plan text in the queue state and return the page it approved. The plan file itself is never edited. */