@staix/vault-mem-ui 0.0.0-stage → 0.0.0

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 (64) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/LICENSE +21 -0
  3. package/README.md +96 -2
  4. package/THIRD_PARTY_NOTICES.md +164 -0
  5. package/bin/vmem-ui.ts +26 -0
  6. package/dist/panel.css +666 -0
  7. package/dist/panel.js +355 -0
  8. package/package.json +53 -4
  9. package/src/client/App.tsx +167 -0
  10. package/src/client/a11y.ts +54 -0
  11. package/src/client/acon.ts +46 -0
  12. package/src/client/components.tsx +243 -0
  13. package/src/client/data.ts +66 -0
  14. package/src/client/fake.ts +48 -0
  15. package/src/client/graph-export.tsx +21 -0
  16. package/src/client/host.ts +80 -0
  17. package/src/client/markdown/parse.ts +620 -0
  18. package/src/client/markdown/render.tsx +270 -0
  19. package/src/client/panel.css +666 -0
  20. package/src/client/panel.tsx +66 -0
  21. package/src/client/prefs.ts +76 -0
  22. package/src/client/standalone.ts +44 -0
  23. package/src/client/store.ts +201 -0
  24. package/src/client/views/assertions.tsx +109 -0
  25. package/src/client/views/common.ts +15 -0
  26. package/src/client/views/history.tsx +205 -0
  27. package/src/client/views/lint.tsx +27 -0
  28. package/src/client/views/log.tsx +64 -0
  29. package/src/client/views/note.tsx +128 -0
  30. package/src/client/views/notes.tsx +34 -0
  31. package/src/client/views/overview.tsx +74 -0
  32. package/src/client/views/promote.tsx +112 -0
  33. package/src/client/views/proposals.tsx +55 -0
  34. package/src/client/views/settings.tsx +57 -0
  35. package/src/client/write.ts +144 -0
  36. package/src/graph/decisionChains.ts +122 -0
  37. package/src/graph/derive.ts +338 -0
  38. package/src/graph/export.ts +44 -0
  39. package/src/graph/insights.ts +254 -0
  40. package/src/graph/labels.ts +67 -0
  41. package/src/graph/layout/client.ts +139 -0
  42. package/src/graph/layout/engine.ts +107 -0
  43. package/src/graph/layout/fa2.d.ts +8 -0
  44. package/src/graph/layout/protocol.ts +70 -0
  45. package/src/graph/layout/worker.ts +132 -0
  46. package/src/graph/model.ts +230 -0
  47. package/src/graph/positions.ts +41 -0
  48. package/src/graph/search.ts +54 -0
  49. package/src/graph/style.ts +301 -0
  50. package/src/graph/target.ts +38 -0
  51. package/src/graph/types.ts +64 -0
  52. package/src/graph/view/GraphView.tsx +279 -0
  53. package/src/graph/view/SidePanels.tsx +141 -0
  54. package/src/graph/view/cache.ts +42 -0
  55. package/src/graph/view/canvas.ts +309 -0
  56. package/src/graph/view/graph-snapshot.ts +75 -0
  57. package/src/graph/view/lod.ts +30 -0
  58. package/src/graph/view/motion.ts +4 -0
  59. package/src/graph/view/state.ts +240 -0
  60. package/src/plugin/assets.ts +33 -0
  61. package/src/plugin/graph.ts +71 -0
  62. package/src/plugin/index.ts +23 -0
  63. package/src/server/cli.ts +99 -0
  64. package/src/server/host.ts +287 -0
@@ -0,0 +1,33 @@
1
+ /**
2
+ * The console takes panel assets as strings, so the plugin reads this package's own build output.
3
+ *
4
+ * This is the one file under `src/` allowed to import `node:fs` (see `scripts/import-boundary.ts`): it imports
5
+ * `readFileSync` alone and calls it with these two fixed `dist/` paths, which the boundary check reads off this
6
+ * file. No other path, no other `node:fs` member and no write can pass that check, so the vault itself stays
7
+ * behind the `@staix/vault-mem` provider.
8
+ */
9
+
10
+ import { readFileSync } from "node:fs";
11
+
12
+ export interface PanelAssets {
13
+ js: string;
14
+ css: string;
15
+ }
16
+
17
+ /** Both reads go through here so one message covers a missing bundle; the call itself stays at the read site. */
18
+ function built(path: string, read: () => string): string {
19
+ try {
20
+ return read();
21
+ } catch (error) {
22
+ const cause = error instanceof Error ? error.message : String(error);
23
+ throw new Error(`the panel bundle is missing (${path}): ${cause}. Build it first with \`bun run build\`.`);
24
+ }
25
+ }
26
+
27
+ /** The one ES module and the one stylesheet the console serves for this panel. */
28
+ export function panelAssets(): PanelAssets {
29
+ return {
30
+ js: built("dist/panel.js", () => readFileSync(new URL("../../dist/panel.js", import.meta.url), "utf8")),
31
+ css: built("dist/panel.css", () => readFileSync(new URL("../../dist/panel.css", import.meta.url), "utf8")),
32
+ };
33
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * The graph panel on top of a vmem provider that may not have one yet. The manifest gains a declared `graph` panel
3
+ * so both hosts route it (acon refuses undeclared panels; the standalone host checks the manifest). A `graph`
4
+ * snapshot goes to the provider first, so a provider that implements vault-mem #266 answers it itself; until then
5
+ * its "unknown panel" reply becomes `{ graph: null, unavailable }` and the panel says why. This is not #266's wire
6
+ * format and makes no claim about it.
7
+ */
8
+
9
+ import type { ConsolePanelManifest, ConsoleProvider } from "@staix/agent-console/contract";
10
+ import { isPanelId } from "../client/prefs.ts";
11
+
12
+ export const GRAPH_PANEL = { id: "graph", title: "Graph", order: 6.5 } as const;
13
+
14
+ export const GRAPH_UNAVAILABLE =
15
+ "this vmem provider does not send a graph snapshot yet (vault-mem #266); update @staix/vault-mem, then reload this panel";
16
+
17
+ /** The manifest with a `graph` panel, unless the provider already declares one. */
18
+ export function withGraphPanel(manifest: ConsolePanelManifest): ConsolePanelManifest {
19
+ if (manifest.panels.some((p) => p.id === GRAPH_PANEL.id)) return manifest;
20
+ return { ...manifest, panels: [...manifest.panels, { ...GRAPH_PANEL }] };
21
+ }
22
+
23
+ /** Declare only panels rendered by this bundle in either host. */
24
+ export function implementedPanelManifest(manifest: ConsolePanelManifest): ConsolePanelManifest {
25
+ return withGraphPanel({ ...manifest, panels: manifest.panels.filter((panel) => isPanelId(panel.id)) });
26
+ }
27
+
28
+ function isUnknownGraphPanel(reply: Record<string, unknown>): boolean {
29
+ return typeof reply.error === "string" && /unknown panel/i.test(reply.error) && !("graph" in reply);
30
+ }
31
+
32
+ /** Snapshot that answers `graph` with an explicit unavailable reply when the provider does not know the panel.
33
+ *
34
+ * A graph reply also carries the provider's declared `capabilities.actions`, because neither host hands the manifest
35
+ * to the panel (`ConsoleHost` has no such member) and the graph's link control may only appear when the provider
36
+ * declares `link`. `actions` is the same list the manifest declares: the provider's own action vocabulary.
37
+ *
38
+ * Two replies are left exactly as the provider sent them. A `changed: false` cursor stub must keep only its own keys,
39
+ * because acon's shell counts an unchanged poll by them (`shell/shell.js` `pollPanel`); with a third key it would push
40
+ * the stub as new data and cache it, replacing the panel's graph. A continuation page needs no declaration either:
41
+ * the assembler reads it from the first page, which is not a `page` request. */
42
+ export function graphAwareSnapshot(snapshot: ConsoleProvider["snapshot"], actions: readonly string[] = []): ConsoleProvider["snapshot"] {
43
+ const capabilities = { actions: [...actions] };
44
+ return async (input) => {
45
+ if (input.panel !== GRAPH_PANEL.id) return snapshot(input);
46
+ let reply: Record<string, unknown>;
47
+ try {
48
+ reply = await snapshot(input);
49
+ } catch (error) {
50
+ if (error instanceof Error && /unknown panel/i.test(error.message)) return { graph: null, unavailable: GRAPH_UNAVAILABLE, capabilities };
51
+ throw error;
52
+ }
53
+ if (isUnknownGraphPanel(reply)) return { graph: null, unavailable: GRAPH_UNAVAILABLE, capabilities };
54
+ if (input.page !== undefined || reply.changed === false) return reply;
55
+ return { ...reply, capabilities };
56
+ };
57
+ }
58
+
59
+ /** The provider with the graph-aware snapshot; every other member is forwarded through a call so bound methods keep working. */
60
+ export function graphProvider(provider: ConsoleProvider, actions: readonly string[] = []): ConsoleProvider {
61
+ const wrapped: ConsoleProvider = {
62
+ assets: provider.assets,
63
+ snapshot: graphAwareSnapshot((input) => provider.snapshot(input), actions),
64
+ action: (input, meta) => provider.action(input, meta),
65
+ };
66
+ if (provider.principalSnapshot) wrapped.principalSnapshot = (input) => provider.principalSnapshot!(input);
67
+ if (provider.principalAction) wrapped.principalAction = (input, meta) => provider.principalAction!(input, meta);
68
+ if (provider.asset) wrapped.asset = (input) => provider.asset!(input);
69
+ if (provider.close) wrapped.close = () => provider.close!();
70
+ return wrapped;
71
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * The `acon` plugin for the vmem tool: `@staix/vault-mem/ui-plugin` still answers every `snapshot` and `action`
3
+ * (so writes keep vmem's validation, receipts and two-step confirmation), and this package's bundle becomes the
4
+ * panel. Wrapping rather than copying keeps one provider behind both hosts. The manifest also declares the graph
5
+ * panel, answered as unavailable until the provider has a graph snapshot (see ./graph.ts).
6
+ */
7
+
8
+ import type { ConsoleContext, ConsolePlugin, ConsoleProvider } from "@staix/agent-console/contract";
9
+ import { plugin as vaultPlugin } from "@staix/vault-mem/ui-plugin";
10
+ import { panelAssets } from "./assets.ts";
11
+ import { graphProvider, implementedPanelManifest } from "./graph.ts";
12
+
13
+ export const plugin: ConsolePlugin = {
14
+ manifest: implementedPanelManifest(vaultPlugin.manifest),
15
+ async open(ctx: ConsoleContext): Promise<ConsoleProvider> {
16
+ const provider = await vaultPlugin.open(ctx);
17
+ // Every member is forwarded through a call, so a member the provider binds to its own instance keeps working.
18
+ // The provider's declared actions ride along with the graph snapshot, so the panel offers only what it declares.
19
+ return { ...graphProvider(provider, plugin.manifest.capabilities?.actions ?? []), assets: panelAssets() };
20
+ },
21
+ };
22
+
23
+ export default plugin;
@@ -0,0 +1,99 @@
1
+ /**
2
+ * `vmem-ui` command logic: open the vault-mem console provider in process and serve it on loopback.
3
+ * File reads of the client bundle live in bin/vmem-ui.ts (a fixed two-file allowlist of this package's dist),
4
+ * so nothing under src/ touches the filesystem.
5
+ */
6
+ import { homedir } from "node:os";
7
+ import { join } from "node:path";
8
+ import plugin from "@staix/vault-mem/ui-plugin";
9
+ import { graphProvider, implementedPanelManifest } from "../plugin/graph.ts";
10
+ import { DEFAULT_IDLE_MS, startHost, type ClientAssets, type Host } from "./host.ts";
11
+
12
+ export interface RunOptions {
13
+ assets: ClientAssets;
14
+ argv: string[];
15
+ env: Record<string, string | undefined>;
16
+ out: (line: string) => void;
17
+ err: (line: string) => void;
18
+ /** Called with the exit code when the server stops on its own (idle). */
19
+ exit: (code: number) => void;
20
+ /** Provider factory; tests replace it. Defaults to the vault-mem console plugin. */
21
+ open?: typeof plugin.open;
22
+ }
23
+
24
+ export const USAGE = `usage: vmem-ui [--port <n>] [--idle-minutes <n>]
25
+ Serves the vault-mem console on 127.0.0.1 and prints a one-time sign-in link.
26
+ The vault is the home vmem resolves: VMEM_HOME, else ~/.agenthub/vmem.
27
+ --port <n> loopback port (default: a free port)
28
+ --idle-minutes <n> exit after this many minutes without a request (default: ${DEFAULT_IDLE_MS / 60_000})`;
29
+
30
+ export function parseArgs(argv: string[]): { port: number; idleMs: number; help: boolean } | { error: string } {
31
+ let port = 0, idleMs = DEFAULT_IDLE_MS, help = false;
32
+ for (let i = 0; i < argv.length; i++) {
33
+ const a = argv[i]!;
34
+ if (a === "-h" || a === "--help") { help = true; continue; }
35
+ if (a === "--port" || a === "--idle-minutes") {
36
+ const raw = argv[++i];
37
+ // Decimal digits only: Number("") is 0, Number("0x10") is 16 and Number(" 80 ") is 80, and none of those is a port.
38
+ const n = raw !== undefined && /^\d+$/.test(raw) ? Number(raw) : NaN;
39
+ if (!Number.isSafeInteger(n) || (a === "--port" && n > 65535) || (a === "--idle-minutes" && n < 1)) {
40
+ return { error: `${a} needs ${a === "--port" ? "a port number from 0 to 65535" : "a whole number of minutes, 1 or more"}; got ${raw === undefined || raw === "" ? "nothing" : raw}` };
41
+ }
42
+ if (a === "--port") port = n; else idleMs = n * 60_000;
43
+ continue;
44
+ }
45
+ return { error: `unknown option ${a}; run vmem-ui --help for the options` };
46
+ }
47
+ return { port, idleMs, help };
48
+ }
49
+
50
+ /** Returns the running host, or null after printing why it could not start. */
51
+ export async function run(options: RunOptions): Promise<Host | null> {
52
+ const parsed = parseArgs(options.argv);
53
+ if ("error" in parsed) { options.err(`vmem-ui: ${parsed.error}`); return null; }
54
+ if (parsed.help) { options.out(USAGE); return null; }
55
+ // The console contract's context takes the family home. vmem resolves the served vault home itself — VMEM_HOME, then
56
+ // a `home` pointer in the default home's config, then `$AGENTHUB_HOME/vmem` — so this value never selects the vault.
57
+ const home = options.env.AGENTHUB_HOME ?? join(homedir(), ".agenthub");
58
+ let provider: Awaited<ReturnType<typeof plugin.open>>;
59
+ try {
60
+ provider = await (options.open ?? plugin.open.bind(plugin))({ home, log: (line) => options.err(line) });
61
+ } catch (e) {
62
+ const msg = e instanceof Error ? e.message : String(e);
63
+ options.err(`vmem-ui: could not open the vault-mem provider: ${msg}; check VMEM_HOME and AGENTHUB_HOME (absolute paths, readable vault registry), then run vmem-ui again`);
64
+ return null;
65
+ }
66
+ let host: Host;
67
+ try {
68
+ const manifest = implementedPanelManifest(plugin.manifest);
69
+ host = startHost({
70
+ provider: graphProvider(provider, manifest.capabilities?.actions ?? []), manifest, assets: options.assets, port: parsed.port, idleMs: parsed.idleMs,
71
+ log: (line) => options.err(line),
72
+ onIdle: () => {
73
+ options.out(`vmem-ui: no requests for ${parsed.idleMs / 60_000} minutes; stopped. Run vmem-ui again to reopen.`);
74
+ options.exit(0);
75
+ },
76
+ });
77
+ } catch (e) {
78
+ await provider.close?.();
79
+ const msg = e instanceof Error ? e.message : String(e);
80
+ options.err(`vmem-ui: could not listen on 127.0.0.1:${parsed.port}: ${msg}; pick another --port or omit it for a free one`);
81
+ return null;
82
+ }
83
+ options.out(`vmem-ui: open this one-time link in your browser (valid 5 minutes):\n${host.issue()}`);
84
+ return host;
85
+ }
86
+
87
+ /**
88
+ * The one shutdown path: close the host (and with it the provider), then exit. Signals and the idle exit both use it,
89
+ * so a close that fails is reported and still ends the process rather than leaving it running with no server.
90
+ */
91
+ export async function shutdown(host: Host, exit: (code: number) => void, log: (line: string) => void = () => {}): Promise<void> {
92
+ try {
93
+ await host.close();
94
+ exit(0);
95
+ } catch (error) {
96
+ log(`vmem-ui: could not close the vault-mem provider: ${error instanceof Error ? error.message : String(error)}; exiting anyway`);
97
+ exit(1);
98
+ }
99
+ }
@@ -0,0 +1,287 @@
1
+ /**
2
+ * Standalone loopback host for the vault-mem console provider (issue #1, "Standalone host").
3
+ * Pattern follows agent-console src/server.ts (H0): one-time ticket, HttpOnly SameSite=Strict session cookie,
4
+ * Host and Origin checks on every request, strict CSP, bounded bodies and idle exit.
5
+ * The server only relays snapshot and action to the provider; it never adds `confirmed` or a fingerprint,
6
+ * so vmem's two-step confirmation stays with the person.
7
+ */
8
+ import type { Server } from "bun";
9
+ import type { ConsolePanelManifest, ConsoleProvider } from "@staix/agent-console/contract";
10
+
11
+ /** Same directives as the acon panel contract: own scripts and styles only, no inline code, no blob:, no other origin. */
12
+ export const CSP = "default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'self' data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'";
13
+ export const DEFAULT_IDLE_MS = 30 * 60_000;
14
+ export const DEFAULT_MAX_BODY_BYTES = 32 * 1024;
15
+ const TICKET_MS = 5 * 60_000;
16
+ const SESSION_MS = 12 * 60 * 60_000;
17
+ const MAX_TICKETS = 16;
18
+
19
+ export interface ClientAssets {
20
+ /** The built standalone client module and stylesheet. */
21
+ js: string;
22
+ css: string;
23
+ }
24
+
25
+ export interface HostOptions {
26
+ provider: ConsoleProvider;
27
+ manifest: ConsolePanelManifest;
28
+ assets: ClientAssets;
29
+ /** 0 picks a free port. */
30
+ port?: number;
31
+ idleMs?: number;
32
+ maxBodyBytes?: number;
33
+ /** Where a provider failure is reported; the 500 reply points the person at these lines. Defaults to stderr. */
34
+ log?: (line: string) => void;
35
+ /** Runs once after the idle close; the command exits here. */
36
+ onIdle?: () => void;
37
+ now?: () => number;
38
+ }
39
+
40
+ export interface Host {
41
+ readonly origin: string;
42
+ readonly port: number;
43
+ /** A new one-time sign-in link, valid for 5 minutes. */
44
+ issue(): string;
45
+ /** Stops serving. Keeps the provider open, so a caller that owns it can close it in its own order. */
46
+ stop(): Promise<void>;
47
+ /** Stops serving, then closes the provider: one shutdown path for a signal and for the idle exit. */
48
+ close(): Promise<void>;
49
+ }
50
+
51
+ /**
52
+ * The loopback origin and the Host/Origin values a browser actually sends for it. A URL drops a default port, so
53
+ * `--port 80` is checked as `127.0.0.1` and `http://127.0.0.1` rather than the `:80` forms no browser sends.
54
+ */
55
+ export function loopback(port: number): { origin: string; hosts: string[]; origins: string[] } {
56
+ const local = new URL(`http://127.0.0.1:${port}`);
57
+ const named = new URL(`http://localhost:${port}`);
58
+ return { origin: local.origin, hosts: [local.host, named.host], origins: [local.origin, named.origin] };
59
+ }
60
+
61
+ /** Panels the page may ask for: the manifest's own, plus inbox and search only where it advertises them. */
62
+ export function allowedPanels(manifest: ConsolePanelManifest): Set<string> {
63
+ const panels = new Set(manifest.panels.map((panel) => panel.id));
64
+ if (manifest.capabilities?.inbox) panels.add("inbox");
65
+ if (manifest.capabilities?.search) panels.add("search");
66
+ return panels;
67
+ }
68
+
69
+ const BASE_HEADERS: Record<string, string> = {
70
+ "Content-Security-Policy": CSP,
71
+ "X-Content-Type-Options": "nosniff",
72
+ "X-Frame-Options": "DENY",
73
+ "Referrer-Policy": "no-referrer",
74
+ "Cache-Control": "no-store",
75
+ "Cross-Origin-Opener-Policy": "same-origin",
76
+ "Cross-Origin-Resource-Policy": "same-origin",
77
+ };
78
+
79
+ const secret = () => Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("base64url");
80
+
81
+ const INDEX_HTML = `<!doctype html>
82
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
83
+ <title>Vault</title><link rel="stylesheet" href="/panel.css"></head>
84
+ <body><main id="vmem-ui-root"></main>
85
+ <script type="module" src="/panel.js"></script></body></html>
86
+ `;
87
+
88
+ class Refusal extends Error {
89
+ constructor(readonly status: number, message: string) { super(message); }
90
+ }
91
+
92
+ /** Reads a request body as JSON, refusing anything over `limit` bytes before and while reading. */
93
+ export async function readJsonBody(req: Request, limit: number): Promise<Record<string, unknown>> {
94
+ const declared = req.headers.get("content-length");
95
+ const tooBig = `request body is over the ${limit} byte limit; send a smaller request`;
96
+ if (declared !== null && Number(declared) > limit) throw new Refusal(413, tooBig);
97
+ // The exact media type: parameters are allowed (they follow the `;`), another JSON-shaped type is not.
98
+ if ((req.headers.get("content-type") ?? "").split(";")[0]!.trim().toLowerCase() !== "application/json") {
99
+ throw new Refusal(415, "request body must be JSON; send it with Content-Type: application/json");
100
+ }
101
+ const chunks: Uint8Array[] = [];
102
+ let size = 0;
103
+ if (req.body) {
104
+ const reader = req.body.getReader();
105
+ for (;;) {
106
+ const { done, value } = await reader.read();
107
+ if (done) break;
108
+ size += value.byteLength;
109
+ if (size > limit) { await reader.cancel(); throw new Refusal(413, tooBig); }
110
+ chunks.push(value);
111
+ }
112
+ }
113
+ let parsed: unknown;
114
+ try { parsed = JSON.parse(new TextDecoder().decode(Buffer.concat(chunks))); } catch {
115
+ throw new Refusal(400, "request body is not valid JSON; send one complete JSON object");
116
+ }
117
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Refusal(400, "request body must be a JSON object; wrap the fields in {}");
118
+ return parsed as Record<string, unknown>;
119
+ }
120
+
121
+ export function startHost(options: HostOptions): Host {
122
+ const { provider, manifest, assets } = options;
123
+ const idleMs = options.idleMs ?? DEFAULT_IDLE_MS;
124
+ const maxBody = options.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES;
125
+ const log = options.log ?? ((line: string) => console.error(line));
126
+ const now = options.now ?? Date.now;
127
+ const tickets = new Map<string, number>();
128
+ const sessions = new Map<string, number>();
129
+ const panels = allowedPanels(manifest);
130
+ let lastSeen = now();
131
+ let stopped = false;
132
+ let timer: ReturnType<typeof setTimeout> | undefined;
133
+ // Filled in right after Bun.serve returns; requests cannot arrive earlier.
134
+ let hosts: string[] = [];
135
+ let origins: string[] = [];
136
+ let cookieName = "";
137
+
138
+ const prune = (m: Map<string, number>) => { const t = now(); for (const [k, exp] of m) if (exp <= t) m.delete(k); };
139
+ const cookieOf = (req: Request) => req.headers.get("cookie")?.split(";").map((v) => v.trim()).find((v) => v.startsWith(`${cookieName}=`))?.slice(cookieName.length + 1);
140
+ const signedIn = (req: Request) => { prune(sessions); const c = cookieOf(req); return c !== undefined && sessions.has(c); };
141
+
142
+ const text = (status: number, body: string, headers: Record<string, string> = {}) =>
143
+ new Response(body, { status, headers: { ...BASE_HEADERS, "Content-Type": "text/plain; charset=utf-8", ...headers } });
144
+ const json = (status: number, body: unknown) =>
145
+ new Response(JSON.stringify(body), { status, headers: { ...BASE_HEADERS, "Content-Type": "application/json; charset=utf-8" } });
146
+ const refuse = (req: Request, status: number, message: string) =>
147
+ new URL(req.url).pathname.startsWith("/api/") ? json(status, { ok: false, error: message }) : text(status, `${message}\n`);
148
+
149
+ const NOT_SIGNED_IN = "not signed in; open the link that vmem-ui printed, or restart vmem-ui for a new one";
150
+
151
+ async function handle(req: Request): Promise<Response> {
152
+ const url = new URL(req.url);
153
+ // Host check before anything else: blocks DNS rebinding to this loopback port.
154
+ if (!hosts.includes(req.headers.get("host") ?? "")) {
155
+ return refuse(req, 421, `host "${req.headers.get("host") ?? ""}" is not this server; open ${origins[0]} instead`);
156
+ }
157
+ const origin = req.headers.get("origin");
158
+ if (origin !== null && !origins.includes(origin)) {
159
+ return refuse(req, 403, `cross-origin request from ${origin} refused; use the vmem-ui page at ${origins[0]}`);
160
+ }
161
+ const site = req.headers.get("sec-fetch-site");
162
+ if (site !== null && !["same-origin", "none"].includes(site)) {
163
+ return refuse(req, 403, "cross-site request refused; open the vmem-ui page directly instead of from another site");
164
+ }
165
+
166
+ if (req.method === "GET" && url.pathname === "/login") {
167
+ prune(tickets);
168
+ const ticket = url.searchParams.get("t") ?? "";
169
+ if (!tickets.delete(ticket)) return text(401, "this sign-in link was already used or has expired; restart vmem-ui to get a new link\n");
170
+ const session = secret();
171
+ sessions.set(session, now() + SESSION_MS);
172
+ return new Response(null, {
173
+ status: 303,
174
+ headers: { ...BASE_HEADERS, Location: "/", "Set-Cookie": `${cookieName}=${session}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${SESSION_MS / 1000}` },
175
+ });
176
+ }
177
+
178
+ if (!signedIn(req)) return refuse(req, 401, NOT_SIGNED_IN);
179
+
180
+ if (req.method === "GET") {
181
+ if (url.pathname === "/") return new Response(INDEX_HTML, { headers: { ...BASE_HEADERS, "Content-Type": "text/html; charset=utf-8" } });
182
+ if (url.pathname === "/panel.js") return new Response(assets.js, { headers: { ...BASE_HEADERS, "Content-Type": "text/javascript; charset=utf-8" } });
183
+ if (url.pathname === "/panel.css") return new Response(assets.css, { headers: { ...BASE_HEADERS, "Content-Type": "text/css; charset=utf-8" } });
184
+ if (url.pathname === "/api/manifest") return json(200, manifest);
185
+ return refuse(req, 404, `no page at ${url.pathname}; open ${origins[0]}/`);
186
+ }
187
+
188
+ if (req.method === "POST" && (url.pathname === "/api/snapshot" || url.pathname === "/api/action")) {
189
+ // State-changing routes need an explicit same-origin Origin header, not just the cookie.
190
+ if (origin === null) return refuse(req, 403, "Origin header missing; send API requests from the vmem-ui page");
191
+ const input = await readJsonBody(req, maxBody);
192
+ if (url.pathname === "/api/snapshot") {
193
+ const panel = typeof input.panel === "string" ? input.panel : "";
194
+ if (!panels.has(panel)) return refuse(req, 400, `unknown panel "${panel}"; use one of ${[...panels].join(", ")}`);
195
+ const after = input.after ?? 0;
196
+ if (typeof after !== "number" || !Number.isSafeInteger(after) || after < 0) {
197
+ return refuse(req, 400, `"after" must be how many items you already have, as a whole number 0 or more; got ${JSON.stringify(input.after)}`);
198
+ }
199
+ return json(200, await provider.snapshot({ ...input, panel, after }));
200
+ }
201
+ if (typeof input.action !== "string" || input.action === "") return refuse(req, 400, "action name missing; send {\"action\": \"<name>\", ...}");
202
+ // Relay only: `confirmed` and `fingerprint` pass through exactly as the person's page sent them.
203
+ return json(200, await provider.action(input as Parameters<ConsoleProvider["action"]>[0], { identity: "local", node: "local", via: "console", actor: { kind: "person", id: "local" } }));
204
+ }
205
+ return refuse(req, 405, `${req.method} ${url.pathname} is not supported; the API takes POST /api/snapshot and POST /api/action`);
206
+ }
207
+
208
+ const server: Server<undefined> = Bun.serve({
209
+ hostname: "127.0.0.1",
210
+ port: options.port ?? 0,
211
+ // Bun's own limit answers with an empty 413 before fetch runs, so it is set out of reach. The bound is enforced in
212
+ // readJsonBody instead: a declared Content-Length over the limit is refused unread, and a streamed body is cancelled
213
+ // as soon as it passes the limit, so at most maxBody bytes plus one chunk are ever held.
214
+ maxRequestBodySize: Number.MAX_SAFE_INTEGER,
215
+ async fetch(req) {
216
+ lastSeen = now();
217
+ armIdle();
218
+ try {
219
+ return await handle(req);
220
+ } catch (err) {
221
+ if (err instanceof Refusal) return refuse(req, err.status, err.message);
222
+ const message = err instanceof Error ? err.message : String(err);
223
+ // The reply names the terminal, so the terminal has to carry the cause and where it came from.
224
+ log(`vmem-ui: ${req.method} ${new URL(req.url).pathname} failed: ${message}`);
225
+ return refuse(req, 500, `the vault provider failed: ${message}; check the vmem-ui terminal and retry`);
226
+ }
227
+ },
228
+ });
229
+ const port = server.port!;
230
+ const bound = loopback(port);
231
+ const origin = bound.origin;
232
+ hosts = bound.hosts;
233
+ origins = bound.origins;
234
+ cookieName = `vmem_ui_${port}`;
235
+
236
+ function armIdle() {
237
+ if (stopped) return;
238
+ if (timer) clearTimeout(timer);
239
+ timer = setTimeout(() => {
240
+ if (stopped) return;
241
+ if (now() - lastSeen < idleMs) return armIdle();
242
+ // Both outcomes stop the process: the server is already down, so a failed close is reported and the exit happens.
243
+ void close().then(
244
+ () => options.onIdle?.(),
245
+ (error) => {
246
+ log(`vmem-ui: could not close the vault-mem provider: ${error instanceof Error ? error.message : String(error)}; stopping anyway`);
247
+ options.onIdle?.();
248
+ },
249
+ );
250
+ }, Math.max(0, idleMs - (now() - lastSeen)));
251
+ }
252
+ armIdle();
253
+
254
+ async function stop() {
255
+ if (stopped) return;
256
+ stopped = true;
257
+ if (timer) clearTimeout(timer);
258
+ tickets.clear();
259
+ sessions.clear();
260
+ await server.stop(true);
261
+ }
262
+
263
+ // One close for the process: a second signal, or the idle timer racing a signal, awaits the promise already in
264
+ // flight instead of returning early and letting a caller exit while the provider is still closing.
265
+ let closing: Promise<void> | undefined;
266
+ function close(): Promise<void> {
267
+ closing ??= (async () => {
268
+ await stop();
269
+ await provider.close?.();
270
+ })();
271
+ return closing;
272
+ }
273
+
274
+ return {
275
+ origin,
276
+ port,
277
+ issue() {
278
+ prune(tickets);
279
+ while (tickets.size >= MAX_TICKETS) tickets.delete(tickets.keys().next().value!);
280
+ const ticket = secret();
281
+ tickets.set(ticket, now() + TICKET_MS);
282
+ return `${origin}/login?t=${ticket}`;
283
+ },
284
+ stop,
285
+ close,
286
+ };
287
+ }