magpie-multi-usage 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,526 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import http from "node:http";
4
+ import path from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import {
7
+ clearGitHubToken,
8
+ ConfigError,
9
+ DEFAULT_CONFIG,
10
+ getPublicConfigView,
11
+ loadConfig,
12
+ sanitizeConfig,
13
+ saveConfig,
14
+ saveGitHubToken,
15
+ validateGitHubToken,
16
+ } from "./config.mjs";
17
+ import { resolveDeviceIdentity } from "./magpie-client.mjs";
18
+ import { createSyncEngine } from "./sync-engine.mjs";
19
+
20
+ export const TOKEN_HEADER = "x-multi-usage-token";
21
+ export const DEFAULT_PORT = DEFAULT_CONFIG.port;
22
+ export const PLUGIN_VERSION = "0.1.1";
23
+
24
+ const MAX_JSON_BODY_BYTES = 256 * 1024;
25
+ const ALLOWED_RANGES = new Set(["today", "7d", "30d", "all"]);
26
+ const SERVER_DIR = path.dirname(fileURLToPath(import.meta.url));
27
+ const UI_DIR = path.join(SERVER_DIR, "ui");
28
+
29
+ const STATIC_ASSETS = Object.freeze({
30
+ "/app.css": { file: "app.css", contentType: "text/css; charset=utf-8", cors: false },
31
+ "/app.js": { file: "app.js", contentType: "application/javascript; charset=utf-8", cors: true },
32
+ "/view-model.mjs": { file: "view-model.mjs", contentType: "application/javascript; charset=utf-8", cors: true },
33
+ });
34
+
35
+ const BASE_SECURITY_HEADERS = Object.freeze({
36
+ "Cache-Control": "no-store, no-cache, must-revalidate",
37
+ "X-Content-Type-Options": "nosniff",
38
+ "Referrer-Policy": "no-referrer",
39
+ });
40
+
41
+ function isLoopbackAddress(remoteAddress) {
42
+ const addr = String(remoteAddress || "").trim().toLowerCase();
43
+ if (!addr) {
44
+ return true;
45
+ }
46
+ if (addr === "::1" || addr === "127.0.0.1") {
47
+ return true;
48
+ }
49
+ const ipv4 = addr.startsWith("::ffff:") ? addr.slice(7) : addr;
50
+ return /^127\.(?:25[0-5]|2[0-4]\d|1?\d?\d)\.(?:25[0-5]|2[0-4]\d|1?\d?\d)\.(?:25[0-5]|2[0-4]\d|1?\d?\d)$/.test(ipv4);
51
+ }
52
+
53
+ function timingSafeEqualString(a, b) {
54
+ const bufA = Buffer.from(String(a || ""), "utf8");
55
+ const bufB = Buffer.from(String(b || ""), "utf8");
56
+ return bufA.length === bufB.length && crypto.timingSafeEqual(bufA, bufB);
57
+ }
58
+
59
+ function readJsonBody(req, maxBytes = MAX_JSON_BODY_BYTES) {
60
+ return new Promise((resolve, reject) => {
61
+ const chunks = [];
62
+ let total = 0;
63
+ let done = false;
64
+
65
+ req.on("data", (chunk) => {
66
+ if (done) {
67
+ return;
68
+ }
69
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), "utf8");
70
+ total += buf.length;
71
+ if (total > maxBytes) {
72
+ done = true;
73
+ const err = new Error("Request body exceeds maximum allowed size.");
74
+ err.statusCode = 413;
75
+ reject(err);
76
+ req.resume();
77
+ return;
78
+ }
79
+ chunks.push(buf);
80
+ });
81
+
82
+ req.on("end", () => {
83
+ if (done) {
84
+ return;
85
+ }
86
+ done = true;
87
+ const raw = Buffer.concat(chunks).toString("utf8").trim();
88
+ if (!raw) {
89
+ resolve({});
90
+ return;
91
+ }
92
+ try {
93
+ const parsed = JSON.parse(raw);
94
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
95
+ const err = new Error("JSON body must be an object.");
96
+ err.statusCode = 400;
97
+ reject(err);
98
+ return;
99
+ }
100
+ resolve(parsed);
101
+ } catch {
102
+ const err = new Error("Invalid JSON request body.");
103
+ err.statusCode = 400;
104
+ reject(err);
105
+ }
106
+ });
107
+
108
+ req.on("error", (err) => {
109
+ if (done) {
110
+ return;
111
+ }
112
+ done = true;
113
+ reject(err);
114
+ });
115
+ });
116
+ }
117
+
118
+ function sendResponse(res, status, contentType, body, extraHeaders = {}) {
119
+ const payload = Buffer.isBuffer(body) ? body : Buffer.from(String(body ?? ""), "utf8");
120
+ res.writeHead(status, {
121
+ "Content-Type": contentType,
122
+ "Content-Length": payload.length,
123
+ ...BASE_SECURITY_HEADERS,
124
+ ...extraHeaders,
125
+ });
126
+ res.end(payload);
127
+ }
128
+
129
+ function sendJson(res, status, value, extraHeaders = {}) {
130
+ sendResponse(res, status, "application/json; charset=utf-8", JSON.stringify(value), extraHeaders);
131
+ }
132
+
133
+ function isNavigationRequest(req) {
134
+ const secFetchMode = String(req.headers?.["sec-fetch-mode"] || "").trim().toLowerCase();
135
+ if (secFetchMode === "navigate") {
136
+ return true;
137
+ }
138
+ const hasOrigin = req.headers?.origin !== undefined;
139
+ const accept = String(req.headers?.accept || "");
140
+ return secFetchMode === "" && !hasOrigin && /\btext\/html\b/i.test(accept);
141
+ }
142
+
143
+ /**
144
+ * Start the local loopback HTTP server for the Magpie plugin page.
145
+ *
146
+ * Security & sandbox invariants:
147
+ * - Binds strictly to 127.0.0.1.
148
+ * - Enforces loopback client address, loopback Host, and absent/null/same-origin Origin.
149
+ * - Requires navigation semantics on token-bearing GET / and GET /index.html
150
+ * (never sending Access-Control-Allow-Origin or Set-Cookie on HTML).
151
+ * - Supports Magpie's sandboxed opaque (null) origin by handling OPTIONS /api/*
152
+ * preflight and returning narrowly scoped CORS headers on JS modules & /api/*.
153
+ * - Authenticates /api/* (except GET /api/health and OPTIONS preflight) via
154
+ * random in-memory X-Multi-Usage-Token header (timingSafeEqual).
155
+ * - Recovers from rolling-restart EADDRINUSE asynchronously without blocking.
156
+ */
157
+ export async function startHttpServer({
158
+ port = DEFAULT_PORT,
159
+ dataDir,
160
+ magpieConfigDir,
161
+ defaults = {},
162
+ env = process.env,
163
+ engine = null,
164
+ uiDir = UI_DIR,
165
+ bgInitialDelayMs = 200,
166
+ bgMaxDelayMs = 2000,
167
+ maxBgRetries = 60,
168
+ } = {}) {
169
+ const requestedPort = Number.isInteger(port) && port >= 0 && port <= 65535 ? port : DEFAULT_PORT;
170
+ const syncEngine = engine || createSyncEngine({
171
+ dataDir,
172
+ magpieConfigDir,
173
+ defaults,
174
+ env,
175
+ pluginVersion: PLUGIN_VERSION,
176
+ });
177
+ const effectiveDataDir = syncEngine.dataDir;
178
+
179
+ const sessionToken = crypto.randomBytes(32).toString("hex");
180
+ let actualPort = requestedPort;
181
+ let allowedHosts = new Set();
182
+ let allowedOrigins = new Set();
183
+ let closed = false;
184
+ let retryTimer = null;
185
+ let readySettled = false;
186
+
187
+ function refreshAllowedEndpoints(boundPort) {
188
+ actualPort = boundPort;
189
+ allowedHosts = new Set([
190
+ `127.0.0.1:${boundPort}`,
191
+ `localhost:${boundPort}`,
192
+ `[::1]:${boundPort}`,
193
+ ]);
194
+ allowedOrigins = new Set([
195
+ `http://127.0.0.1:${boundPort}`,
196
+ `http://localhost:${boundPort}`,
197
+ `http://[::1]:${boundPort}`,
198
+ ]);
199
+ }
200
+ refreshAllowedEndpoints(requestedPort);
201
+
202
+ function isHostAllowed(req) {
203
+ const host = String(req.headers?.host || "").trim().toLowerCase();
204
+ return Boolean(host) && allowedHosts.has(host);
205
+ }
206
+
207
+ function isOriginAllowed(req) {
208
+ const origin = req.headers?.origin;
209
+ if (origin === undefined || origin === "null") {
210
+ return true;
211
+ }
212
+ return allowedOrigins.has(String(origin).trim().toLowerCase());
213
+ }
214
+
215
+ function buildScopedCorsHeaders(req) {
216
+ const origin = req.headers?.origin;
217
+ const allowOrigin = origin === "null"
218
+ ? "null"
219
+ : origin && allowedOrigins.has(String(origin).trim().toLowerCase())
220
+ ? String(origin).trim()
221
+ : "null";
222
+ return {
223
+ "Access-Control-Allow-Origin": allowOrigin,
224
+ "Access-Control-Allow-Headers": "Content-Type, X-Multi-Usage-Token",
225
+ "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
226
+ Vary: "Origin",
227
+ };
228
+ }
229
+
230
+ async function handleApi(req, res, method, pathname, searchParams) {
231
+ const corsHeaders = buildScopedCorsHeaders(req);
232
+
233
+ if (method === "OPTIONS") {
234
+ res.writeHead(204, {
235
+ ...BASE_SECURITY_HEADERS,
236
+ ...corsHeaders,
237
+ });
238
+ res.end();
239
+ return;
240
+ }
241
+
242
+ if (method === "GET" && pathname === "/api/health") {
243
+ sendJson(res, 200, { ok: true, version: PLUGIN_VERSION }, corsHeaders);
244
+ return;
245
+ }
246
+
247
+ const presentedToken = req.headers?.[TOKEN_HEADER];
248
+ if (!timingSafeEqualString(presentedToken, sessionToken)) {
249
+ sendJson(res, 401, { error: "Unauthorized" }, corsHeaders);
250
+ return;
251
+ }
252
+
253
+ let body = {};
254
+ if (method === "POST") {
255
+ try {
256
+ body = await readJsonBody(req);
257
+ } catch (err) {
258
+ sendJson(res, err.statusCode || 400, { error: err.message }, corsHeaders);
259
+ return;
260
+ }
261
+ }
262
+
263
+ if (method === "GET" && pathname === "/api/summary") {
264
+ const range = searchParams.get("range") || "7d";
265
+ if (!ALLOWED_RANGES.has(range)) {
266
+ sendJson(res, 400, { error: `Invalid range "${range}". Expected today, 7d, 30d, or all.` }, corsHeaders);
267
+ return;
268
+ }
269
+ const deviceFilter = searchParams.get("device") || "all";
270
+ const summary = await syncEngine.getSummary({ range, deviceFilter });
271
+ sendJson(res, 200, summary, corsHeaders);
272
+ return;
273
+ }
274
+
275
+ if (method === "POST" && pathname === "/api/refresh") {
276
+ const range = typeof body.range === "string" && ALLOWED_RANGES.has(body.range) ? body.range : "7d";
277
+ const deviceFilter = typeof body.device === "string" && body.device.trim() ? body.device.trim() : "all";
278
+ const result = await syncEngine.refresh({
279
+ range,
280
+ deviceFilter,
281
+ push: body.push !== false,
282
+ pull: body.pull !== false,
283
+ forcePush: true,
284
+ });
285
+ sendJson(res, 200, result, corsHeaders);
286
+ return;
287
+ }
288
+
289
+ if (method === "GET" && pathname === "/api/config") {
290
+ const identity = await resolveDeviceIdentity({
291
+ dataDir: effectiveDataDir,
292
+ magpieConfigDir,
293
+ env,
294
+ });
295
+ const view = await getPublicConfigView(effectiveDataDir, {
296
+ deviceId: identity.deviceId,
297
+ defaults,
298
+ env,
299
+ });
300
+ sendJson(res, 200, view, corsHeaders);
301
+ return;
302
+ }
303
+
304
+ if (method === "POST" && pathname === "/api/config") {
305
+ try {
306
+ // Validate both config fields and optional token upfront before writing either file.
307
+ const currentCfg = await loadConfig(effectiveDataDir, { defaults });
308
+ sanitizeConfig(body, currentCfg);
309
+ const wantsClear = body.clearToken === true;
310
+ const hasNewToken = typeof body.githubToken === "string" && body.githubToken.trim() !== "";
311
+ if (!wantsClear && hasNewToken) {
312
+ validateGitHubToken(body.githubToken);
313
+ }
314
+
315
+ if (wantsClear) {
316
+ await clearGitHubToken(effectiveDataDir);
317
+ } else if (hasNewToken) {
318
+ await saveGitHubToken(effectiveDataDir, body.githubToken);
319
+ }
320
+ await saveConfig(effectiveDataDir, body, { defaults });
321
+
322
+ const identity = await resolveDeviceIdentity({
323
+ dataDir: effectiveDataDir,
324
+ magpieConfigDir,
325
+ env,
326
+ });
327
+ const view = await getPublicConfigView(effectiveDataDir, {
328
+ deviceId: identity.deviceId,
329
+ defaults,
330
+ env,
331
+ });
332
+ sendJson(res, 200, view, corsHeaders);
333
+ } catch (err) {
334
+ const status = err instanceof ConfigError ? 400 : 500;
335
+ sendJson(res, status, { error: err.message, code: err.code || "CONFIG_ERROR" }, corsHeaders);
336
+ }
337
+ return;
338
+ }
339
+
340
+ if (method === "POST" && pathname === "/api/test-connection") {
341
+ const result = await syncEngine.testConnection({
342
+ repo: typeof body.repo === "string" ? body.repo : undefined,
343
+ branch: typeof body.branch === "string" ? body.branch : undefined,
344
+ prefix: typeof body.prefix === "string" ? body.prefix : undefined,
345
+ token: typeof body.githubToken === "string" && body.githubToken.trim()
346
+ ? body.githubToken.trim()
347
+ : undefined,
348
+ });
349
+ sendJson(res, result.ok ? 200 : 400, result, corsHeaders);
350
+ return;
351
+ }
352
+
353
+ sendJson(res, 404, { error: "Not Found" }, corsHeaders);
354
+ }
355
+
356
+ const server = http.createServer(async (req, res) => {
357
+ try {
358
+ if (!isLoopbackAddress(req.socket?.remoteAddress)) {
359
+ sendResponse(res, 403, "text/plain; charset=utf-8", "Forbidden");
360
+ return;
361
+ }
362
+ if (!isHostAllowed(req) || !isOriginAllowed(req)) {
363
+ sendResponse(res, 403, "text/plain; charset=utf-8", "Forbidden host or origin");
364
+ return;
365
+ }
366
+
367
+ const method = String(req.method || "GET").toUpperCase();
368
+ const parsedUrl = new URL(String(req.url || "/"), `http://127.0.0.1:${actualPort || 80}`);
369
+ const pathname = parsedUrl.pathname || "/";
370
+
371
+ if (pathname.startsWith("/api/")) {
372
+ await handleApi(req, res, method, pathname, parsedUrl.searchParams);
373
+ return;
374
+ }
375
+
376
+ if (method === "GET" && (pathname === "/" || pathname === "/index.html")) {
377
+ if (!isNavigationRequest(req)) {
378
+ sendResponse(res, 403, "text/plain; charset=utf-8", "Navigation request required");
379
+ return;
380
+ }
381
+ const nonce = crypto.randomBytes(16).toString("base64");
382
+ const template = await fs.readFile(path.join(uiDir, "index.html"), "utf8");
383
+ const bootstrapTag = `<script nonce="${nonce}">window.__MULTI_USAGE_TOKEN__=${JSON.stringify(sessionToken)};</script>`;
384
+ const html = template.includes("<!--MULTI_USAGE_BOOTSTRAP-->")
385
+ ? template.replace("<!--MULTI_USAGE_BOOTSTRAP-->", bootstrapTag)
386
+ : template.replace("</head>", `${bootstrapTag}\n</head>`);
387
+
388
+ sendResponse(res, 200, "text/html; charset=utf-8", html, {
389
+ "Content-Security-Policy": `default-src 'self'; script-src 'self' 'nonce-${nonce}'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'`,
390
+ });
391
+ return;
392
+ }
393
+
394
+ if (method === "GET" && Object.prototype.hasOwnProperty.call(STATIC_ASSETS, pathname)) {
395
+ const asset = STATIC_ASSETS[pathname];
396
+ const content = await fs.readFile(path.join(uiDir, asset.file));
397
+ const extraHeaders = asset.cors
398
+ ? {
399
+ "Access-Control-Allow-Origin": buildScopedCorsHeaders(req)["Access-Control-Allow-Origin"],
400
+ Vary: "Origin",
401
+ }
402
+ : {};
403
+ sendResponse(res, 200, asset.contentType, content, extraHeaders);
404
+ return;
405
+ }
406
+
407
+ sendResponse(res, 404, "text/plain; charset=utf-8", "Not Found");
408
+ } catch (error) {
409
+ sendJson(res, 500, { error: error?.message || "Internal server error" });
410
+ }
411
+ });
412
+
413
+ function tryBindOnce() {
414
+ return new Promise((resolve, reject) => {
415
+ const onError = (err) => {
416
+ server.off("listening", onListening);
417
+ reject(err);
418
+ };
419
+ const onListening = () => {
420
+ server.off("error", onError);
421
+ const addr = server.address();
422
+ const boundPort = typeof addr === "object" && addr ? addr.port : requestedPort;
423
+ refreshAllowedEndpoints(boundPort);
424
+ resolve(boundPort);
425
+ };
426
+ server.once("error", onError);
427
+ server.once("listening", onListening);
428
+ server.listen(requestedPort, "127.0.0.1");
429
+ });
430
+ }
431
+
432
+ let resolveReady;
433
+ let rejectReady;
434
+ const ready = new Promise((res, rej) => {
435
+ resolveReady = (val) => {
436
+ if (!readySettled) {
437
+ readySettled = true;
438
+ res(val);
439
+ }
440
+ };
441
+ rejectReady = (err) => {
442
+ if (!readySettled) {
443
+ readySettled = true;
444
+ rej(err);
445
+ }
446
+ };
447
+ });
448
+
449
+ async function close() {
450
+ closed = true;
451
+ if (retryTimer) {
452
+ clearTimeout(retryTimer);
453
+ retryTimer = null;
454
+ }
455
+ resolveReady(null);
456
+ if (server.listening) {
457
+ await new Promise((resolve) => server.close(resolve));
458
+ }
459
+ }
460
+
461
+ let listening = false;
462
+ try {
463
+ const boundPort = await tryBindOnce();
464
+ listening = true;
465
+ resolveReady(boundPort);
466
+ } catch (err) {
467
+ if (err?.code !== "EADDRINUSE") {
468
+ rejectReady(err);
469
+ throw err;
470
+ }
471
+
472
+ let attempt = 0;
473
+ const scheduleRetry = () => {
474
+ if (closed) {
475
+ resolveReady(null);
476
+ return;
477
+ }
478
+ if (attempt >= maxBgRetries) {
479
+ rejectReady(err);
480
+ return;
481
+ }
482
+ const delayMs = Math.min(bgMaxDelayMs, bgInitialDelayMs * (2 ** Math.min(attempt, 6)));
483
+ attempt += 1;
484
+ retryTimer = setTimeout(async () => {
485
+ retryTimer = null;
486
+ if (closed) {
487
+ resolveReady(null);
488
+ return;
489
+ }
490
+ try {
491
+ const boundPort = await tryBindOnce();
492
+ if (closed) {
493
+ await new Promise((resolve) => server.close(resolve));
494
+ resolveReady(null);
495
+ return;
496
+ }
497
+ listening = true;
498
+ resolveReady(boundPort);
499
+ } catch (retryErr) {
500
+ if (retryErr?.code === "EADDRINUSE") {
501
+ scheduleRetry();
502
+ } else {
503
+ rejectReady(retryErr);
504
+ }
505
+ }
506
+ }, delayMs);
507
+ if (typeof retryTimer.unref === "function") {
508
+ retryTimer.unref();
509
+ }
510
+ };
511
+ scheduleRetry();
512
+ }
513
+
514
+ return {
515
+ get listening() {
516
+ return listening;
517
+ },
518
+ get port() {
519
+ return actualPort;
520
+ },
521
+ token: sessionToken,
522
+ server,
523
+ ready,
524
+ close,
525
+ };
526
+ }