Files
plugins/packages/amp-usage/lib/server.mjs
T
ming_jiang 4b0aef5327 amp-usage: Amp usage page with background collection; day-card 0.3.1 (#1000)
Adds packages/amp-usage (@magpie-community/page-amp-usage 0.1.0). It is a magpie page that reads Amp's local thread files and the gateway's usage.jsonl and shows per-day usage. The service listens on loopback only and requires a per-start service token on every API call. The page that carries the token is served only to a navigation (Sec-Fetch-Mode). The gateway log is read incrementally from a saved offset, whole lines only, and is re-indexed on rotation. The UI words are in ui/words.js (en, zh).

Also bumps packages/day-card to 0.3.1.

Round 3 (13c1f33) adds three things:
- a test that bytes before the gateway-log offset are never re-read;
- ui.test.mjs, which checks that every error code the server can return has words in each language, and that an unknown code falls back;
- words.js, moved out of app.js, served at /words.js and included in the pack.

What ran, at 13c1f33 merged with main 14187408, on mica:
- amp-usage `node --test`: 47/47.
- `bun test packages/amp-usage packages/day-card`: 65 pass, 0 fail.
- `bun scripts/check.mjs`, all packages: ok.
- `npm pack --dry-run`: amp-usage 0.1.0 has 19 files including ui/words.js; day-card 0.3.1 has 17 files.
- Root `bun test` with a temp HOME: 8362 pass, 0 fail (8382 tests, 590 files).
- Render smoke in Chromium and WebKit at 1200 and 420px, en and zh: words.js loads, both languages show their own words, no page errors, no horizontal overflow.

Broken by hand, each run with node and bun:
- collector.mjs:102 made to re-read the whole file every scan: the new offset test goes red.
- `const cut = buf.length`, so a partial line is taken: red.
- Raw error codes shown instead of their words (`w.err[code] || code`): red.
- A zh string deleted: red.

Not tried:
- A real Amp account or the real `amp` CLI.
- Changing the auto-refresh default from 300 to 60 fails no test. The author left it untested and round 2 called it optional.

Rounds 1 and 2 also ran the 1M-line log probe (rss steady at about 363MB, scans of 70 to 114ms after the first), the bad-record and paging probes, and the full render matrix including dark mode.
2026-11-11 21:43:59 +08:00

164 lines
5.6 KiB
JavaScript

import { createServer } from "node:http";
import { randomBytes, timingSafeEqual } from "node:crypto";
import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { createCollector, acquireLock } from "./collector.mjs";
const ui = fileURLToPath(new URL("../ui/", import.meta.url));
export async function startServer({
port = 3497,
dataDir,
configDir,
options = {},
collector: injected,
} = {}) {
if (!Number.isInteger(port) || port < 0 || port > 65535)
throw new Error("Invalid service port.");
const release = await acquireLock(dataDir);
let collector;
try {
collector =
injected || (await createCollector({ dataDir, configDir, options }));
} catch (e) {
await release();
throw e;
}
const token = randomBytes(32).toString("hex");
let actualPort;
const send = (res, code, body, type = "application/json") => {
res.writeHead(code, {
"Content-Type": type,
"Cache-Control": "no-store",
"X-Content-Type-Options": "nosniff",
"Referrer-Policy": "no-referrer",
});
res.end(type === "application/json" ? JSON.stringify(body) : body);
};
const server = createServer(async (req, res) => {
try {
const host = req.headers.host;
if (
![`127.0.0.1:${actualPort}`, `localhost:${actualPort}`].includes(host)
)
return send(res, 403, { error: "Invalid host." });
const url = new URL(req.url, `http://${host}`);
const origin = req.headers.origin;
const originOK =
!origin || origin === "null" || origin === `http://${host}`;
if (!originOK) return send(res, 403, { error: "Invalid origin." });
if (url.pathname.startsWith("/api/")) {
if (req.method === "OPTIONS") {
res.setHeader(
"Access-Control-Allow-Origin",
origin || `http://${host}`,
);
res.setHeader(
"Access-Control-Allow-Headers",
"Content-Type, X-Amp-Usage-Token",
);
res.setHeader("Access-Control-Allow-Methods", "GET, POST");
res.setHeader("Vary", "Origin");
return send(res, 204, "", "text/plain");
}
const given = Buffer.from(
String(req.headers["x-amp-usage-token"] || ""),
);
const expected = Buffer.from(token);
if (
given.length !== expected.length ||
!timingSafeEqual(given, expected)
)
return send(res, 403, {
error: "Reopen the Amp usage page to reconnect.",
code: "reconnect",
});
res.setHeader(
"Access-Control-Allow-Origin",
origin || `http://${host}`,
);
res.setHeader("Vary", "Origin");
if (url.pathname === "/api/status" && req.method === "GET")
return send(res, 200, collector.view());
if (req.method !== "POST")
return send(res, 405, { error: "Method not allowed." });
if (
String(req.headers["content-type"]).split(";")[0] !==
"application/json"
)
return send(res, 415, { error: "Expected JSON." });
let raw = "";
for await (const chunk of req) {
raw += chunk;
if (Buffer.byteLength(raw) > 4096)
return send(res, 413, { error: "Request too large." });
}
try {
JSON.parse(raw);
} catch {
return send(res, 400, { error: "Invalid JSON." });
}
if (url.pathname === "/api/refresh") {
// The page polls status; a long cloud export never holds its HTTP request.
void collector.run().catch(() => {});
return send(res, 202, collector.view());
}
return send(res, 404, { error: "Not found." });
}
if (req.method !== "GET")
return send(res, 405, { error: "Method not allowed." });
const files = {
"/": ["index.html", "text/html; charset=utf-8"],
"/app.js": ["app.js", "text/javascript; charset=utf-8"],
"/words.js": ["words.js", "text/javascript; charset=utf-8"],
"/style.css": ["style.css", "text/css; charset=utf-8"],
};
const file = files[url.pathname];
if (!file) return send(res, 404, "Not found", "text/plain");
// The page carries the token, so only a navigation may read it.
const mode = req.headers["sec-fetch-mode"];
if (file[0] === "index.html" && mode && mode !== "navigate")
return send(res, 403, "Forbidden", "text/plain");
let text = await readFile(join(ui, file[0]), "utf8");
if (file[0] === "index.html")
text = text.replace("__SERVICE_TOKEN__", token);
const self = `http://127.0.0.1:${actualPort} http://localhost:${actualPort}`;
res.setHeader(
"Content-Security-Policy",
`default-src 'none'; script-src 'self' ${self}; style-src 'self' ${self}; connect-src 'self' ${self}; base-uri 'none'; form-action 'none'`,
);
return send(res, 200, text, file[1]);
} catch {
if (!res.headersSent)
send(res, 500, {
error: "Local service error. Check the plugin log.",
code: "serviceError",
});
else res.end();
}
});
try {
await new Promise((resolve, reject) => {
server.once("error", reject);
server.listen(port, "127.0.0.1", resolve);
});
actualPort = server.address().port;
} catch (e) {
await collector.close();
await release();
throw e;
}
return {
port: actualPort,
collector,
async close() {
await collector.close();
await new Promise((resolve) => {
server.close(resolve);
server.closeAllConnections();
});
await release();
},
};
}