neurastream 0.3.18 → 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.
- package/README.md +88 -490
- package/package.json +1 -1
- package/src/adapters/index.ts +3 -2
- package/src/adapters/omp/adapter.ts +2 -1
- package/src/adapters/omp/auto-close.ts +64 -0
- package/src/adapters/omp/chat-commands.ts +161 -0
- package/src/adapters/omp/inbox.ts +221 -0
- package/src/adapters/omp/index.ts +138 -1050
- package/src/adapters/omp/launch.ts +35 -9
- package/src/adapters/omp/rate-limit-controller.ts +196 -0
- package/src/adapters/omp/rollover-controller.ts +334 -0
- package/src/adapters/omp/types.ts +143 -0
- package/src/cli/claim.ts +1 -3
- package/src/cli/commands.ts +33 -2
- package/src/cli/dispatch.ts +55 -30
- package/src/cli/guard.ts +0 -3
- package/src/cli/incident.ts +2 -2
- package/src/cli/metrics.ts +1 -1
- package/src/cli/recall.ts +6 -8
- package/src/cli/results-build.ts +2 -4
- package/src/cli/workspace.ts +13 -5
- package/src/core/adapter.ts +16 -0
- package/src/core/autonomy.ts +24 -21
- package/src/core/blockers.ts +326 -30
- package/src/core/file-lock.ts +71 -12
- package/src/core/guards/plan-edit.ts +338 -0
- package/src/core/guards/planner.ts +70 -0
- package/src/core/guards/review.ts +391 -0
- package/src/core/guards/spawn.ts +699 -0
- package/src/core/guards/state.ts +581 -0
- package/src/core/guards/stop.ts +235 -0
- package/src/core/guards/tool.ts +541 -0
- package/src/core/guards.ts +12 -2661
- package/src/core/incidents.ts +134 -99
- package/src/core/machine-guard.ts +23 -5
- package/src/core/main-start.ts +11 -9
- package/src/core/mr-sweep.ts +4 -2
- package/src/core/notify.ts +15 -15
- package/src/core/owner-log.ts +19 -17
- package/src/core/owner-topics.ts +38 -48
- package/src/core/owner-ui/auth.ts +164 -0
- package/src/core/owner-ui/data.ts +437 -0
- package/src/core/owner-ui/handlers.ts +250 -0
- package/src/core/owner-ui/messages.ts +209 -0
- package/src/core/owner-ui/render.ts +714 -0
- package/src/core/owner-ui/results.ts +266 -0
- package/src/core/owner-ui/server.ts +142 -0
- package/src/core/owner-ui.ts +11 -2118
- package/src/core/page-notes.ts +25 -0
- package/src/core/pages.ts +452 -78
- package/src/core/plan-approval.ts +24 -26
- package/src/core/queue/lib.ts +170 -137
- package/src/core/queue-cancel.ts +29 -15
- package/src/core/queue-check.ts +5 -7
- package/src/core/queue-close.ts +54 -29
- package/src/core/queue-finished.ts +9 -10
- package/src/core/queue-migrate.ts +1 -3
- package/src/core/queue-trim.ts +2 -4
- package/src/core/results.ts +0 -2
- package/src/core/rollover.ts +2 -3
- package/src/core/secret-redact.ts +65 -14
- package/src/core/tailscale.ts +79 -3
- package/src/core/team-client.ts +18 -6
- package/src/core/uninstall.ts +2 -0
- package/src/core/watch.ts +3 -2
- package/src/core/queue/env.ts +0 -14
package/src/core/page-notes.ts
CHANGED
|
@@ -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,87 +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
|
-
import { stateDirPath } from "./queue/lib.ts";
|
|
9
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";
|
|
10
10
|
import type { Tailscale } from "./tailscale.ts";
|
|
11
11
|
|
|
12
|
-
export interface PagesServer {
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
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("&", "&")
|
|
49
|
+
.replaceAll("<", "<")
|
|
50
|
+
.replaceAll(">", ">")
|
|
51
|
+
.replaceAll('"', """)
|
|
52
|
+
.replaceAll("'", "'");
|
|
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&¬es[i].note===""){notes[i].quote=quote;paint();return;}
|
|
56
165
|
}
|
|
57
|
-
if (url.pathname !== "/_notes") return plain("method not allowed", 405);
|
|
58
|
-
if (req.headers.get("origin") !== `http://${req.headers.get("host")}`) return plain("forbidden: origin is not this page", 403);
|
|
59
|
-
let body: unknown; try { body = await req.json(); } catch { return plain("bad request: not JSON", 400); }
|
|
60
|
-
const stored = appendPageNotes(body, opts.cfg, login ?? "loopback");
|
|
61
|
-
return stored === null ? plain("no notes to submit", 400) : Response.json({ stored });
|
|
62
|
-
}
|
|
63
|
-
// What the Approve bar asks on load: the notes still open on this page. A page with no plan has none.
|
|
64
|
-
if (url.pathname === "/_approve") {
|
|
65
|
-
const page = url.searchParams.get("page") ?? "";
|
|
66
|
-
const record = page === "" ? null : readPagePlan(root, page);
|
|
67
|
-
if (record === null) return plain("not found: no plan is published as this page", 404);
|
|
68
|
-
return Response.json({ open: openNoteIds(opts.cfg, page), problems: [...record.missing, ...record.thin] });
|
|
69
166
|
}
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
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.";
|
|
80
204
|
}
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
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) };
|
|
87
461
|
}
|