@kehto/paja 0.32.1 → 0.33.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.
@@ -52,6 +52,9 @@ var DEFAULT_THEME_VALUES = {
52
52
  title: "Kehto Paja"
53
53
  };
54
54
  function normalizePajaSimulation(raw) {
55
+ if (raw && Object.prototype.hasOwnProperty.call(raw, "firewall")) {
56
+ throw new PajaSimulationError("simulation.firewall was removed; approve exact scopes in Paja Firewall grants.");
57
+ }
55
58
  const domainOverrides = raw?.capabilities?.domains ?? {};
56
59
  const domains = Object.fromEntries(
57
60
  PAJA_SIMULATION_DOMAINS.map((domain) => [domain, domainOverrides[domain] ?? true])
@@ -146,9 +149,6 @@ function normalizePajaSimulation(raw) {
146
149
  acl: {
147
150
  mode: raw?.acl?.mode ?? "allow"
148
151
  },
149
- firewall: {
150
- mode: raw?.firewall?.mode ?? "observe"
151
- },
152
152
  identity: {
153
153
  mode: identityMode,
154
154
  pubkey: identityMode === "fixed" ? pubkey : ""
@@ -261,6 +261,9 @@ function loadPajaConfigFile(configPath) {
261
261
  if (!isRecord(parsed)) {
262
262
  throw new PajaSimulationError(`Invalid --config "${configPath}": expected a JSON object.`);
263
263
  }
264
+ if (isRecord(parsed.simulation) && Object.prototype.hasOwnProperty.call(parsed.simulation, "firewall")) {
265
+ throw new PajaSimulationError("simulation.firewall was removed; approve exact scopes in Paja Firewall grants.");
266
+ }
264
267
  return parsed;
265
268
  }
266
269
  function resolvePajaRawOptions(raw) {
@@ -280,6 +283,9 @@ function mergePajaRawOptions(base, override) {
280
283
  };
281
284
  }
282
285
  function mergeSimulationOptions(base, override) {
286
+ if (base && Object.prototype.hasOwnProperty.call(base, "firewall") || override && Object.prototype.hasOwnProperty.call(override, "firewall")) {
287
+ throw new PajaSimulationError("simulation.firewall was removed; approve exact scopes in Paja Firewall grants.");
288
+ }
283
289
  if (!base) return override;
284
290
  if (!override) return base;
285
291
  return {
@@ -292,7 +298,6 @@ function mergeSimulationOptions(base, override) {
292
298
  }
293
299
  },
294
300
  acl: { ...base.acl, ...override.acl },
295
- firewall: { ...base.firewall, ...override.firewall },
296
301
  identity: { ...base.identity, ...override.identity },
297
302
  relay: { ...base.relay, ...override.relay },
298
303
  storage: { ...base.storage, ...override.storage },
@@ -589,6 +594,8 @@ function renderPajaHtml(config) {
589
594
  .section-chevron { transition: transform 120ms; }
590
595
  .section[open] > summary .section-chevron { transform: rotate(90deg); }
591
596
  .section-body { padding: 0 12px 12px; display: grid; gap: 8px; }
597
+ .kehto-approval-ui, .kehto-approval-ui section, .kehto-approval-ui li { min-width: 0; max-width: 100%; overflow-wrap: anywhere; }
598
+ .kehto-approval-ui button { white-space: normal; }
592
599
  .resource-servers { display: grid; gap: 8px; }
593
600
  .resource-servers > label { position: absolute; width: 1px; height: 1px; padding: 0; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
594
601
  .section-title { color: var(--accent); font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 0; }
@@ -760,6 +767,10 @@ function renderPajaHtml(config) {
760
767
  <div class="switch-grid" id="interface-toggles"></div>
761
768
  <p class="hint" id="paja-fs-support" role="status"></p>
762
769
  </div></details>
770
+ <details class="section" id="paja-section-permissions" data-paja-section="permissions" open>
771
+ <summary class="section-title">Firewall permissions<span class="section-chevron" aria-hidden="true">\u203A</span></summary><div class="section-body">
772
+ <div id="paja-permission-ui"></div>
773
+ </div></details>
763
774
  <details class="section" id="paja-section-acl" data-paja-section="acl" open>
764
775
  <summary class="section-title">ACL<span class="section-chevron" aria-hidden="true">\u203A</span></summary><div class="section-body">
765
776
  <div class="acl-grid" id="acl-controls"></div>
@@ -1025,6 +1036,7 @@ import {
1025
1036
  // src/browser-resource.ts
1026
1037
  import { verifyBlobHash } from "@kehto/nip/5d";
1027
1038
  import {
1039
+ ResourceAuthorizationError,
1028
1040
  ResourceServiceError
1029
1041
  } from "@kehto/services";
1030
1042
  var PAJA_RESOURCE_MAX_BYTES = 10 * 1024 * 1024;
@@ -1356,6 +1368,8 @@ function formatNappletManifestKinds() {
1356
1368
  var PAJA_LEGACY_COMPATIBILITY_DOMAIN = `i${"fc"}`;
1357
1369
  var PAJA_UPSTREAM_WEB_DOMAINS = [
1358
1370
  "ble",
1371
+ "blossom",
1372
+ "catalog",
1359
1373
  "common",
1360
1374
  "config",
1361
1375
  "count",
@@ -1372,14 +1386,17 @@ var PAJA_UPSTREAM_WEB_DOMAINS = [
1372
1386
  "lists",
1373
1387
  "llm",
1374
1388
  "media",
1389
+ "navigation",
1375
1390
  "notify",
1376
1391
  "outbox",
1377
1392
  "relay",
1378
1393
  "resource",
1379
1394
  "serial",
1380
1395
  "shell",
1396
+ "soulseek",
1381
1397
  "storage",
1382
1398
  "theme",
1399
+ "torrent",
1383
1400
  "upload",
1384
1401
  "webrtc"
1385
1402
  ];
@@ -1698,6 +1715,7 @@ var BrowserIntentController = class {
1698
1715
  /** Complete an already accepted delivery. Kept public for host diagnostics and tests. */
1699
1716
  async dispatch(params) {
1700
1717
  const dispatch = freezeDispatch(params);
1718
+ if (dispatch.signal?.aborted) throw new Error("intent target cancelled");
1701
1719
  let reason = "no-current-target";
1702
1720
  for (let attempt = 1; attempt <= this.maxAttempts; attempt += 1) {
1703
1721
  let generation;
@@ -1717,6 +1735,7 @@ var BrowserIntentController = class {
1717
1735
  reason = "ready-failed";
1718
1736
  continue;
1719
1737
  }
1738
+ if (dispatch.signal?.aborted) throw new Error("intent target cancelled");
1720
1739
  if (!await this.options.isCurrent(generation)) {
1721
1740
  reason = "no-current-target";
1722
1741
  continue;
@@ -1756,7 +1775,8 @@ function freezeDispatch(params) {
1756
1775
  convention: params.convention,
1757
1776
  ...params.payload === void 0 ? {} : { payload },
1758
1777
  ...behavior === void 0 ? {} : { behavior },
1759
- ...params.sourceWindowId === void 0 ? {} : { sourceWindowId: params.sourceWindowId }
1778
+ ...params.sourceWindowId === void 0 ? {} : { sourceWindowId: params.sourceWindowId },
1779
+ ...params.signal === void 0 ? {} : { signal: params.signal }
1760
1780
  });
1761
1781
  }
1762
1782
  function freezeValue(value, seen = /* @__PURE__ */ new WeakMap()) {
@@ -1973,6 +1993,131 @@ function postPajaIntentLauncherMessage(frame, message) {
1973
1993
 
1974
1994
  // src/server.ts
1975
1995
  import { createServer } from "http";
1996
+
1997
+ // src/server-resource-transport.ts
1998
+ import { request as httpRequest } from "http";
1999
+ import { request as httpsRequest } from "https";
2000
+ import { lookup as dnsLookup } from "dns/promises";
2001
+ import { isIP } from "net";
2002
+ var RESOURCE_MAX_BYTES = 10 * 1024 * 1024;
2003
+ var RESOURCE_TIMEOUT_MS = 3e4;
2004
+ async function fetchPinnedResource(input, signal) {
2005
+ const url = new URL(input.href);
2006
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password) {
2007
+ throw new Error("Invalid resource URL");
2008
+ }
2009
+ const hostname = url.hostname.replace(/^\[|\]$/gu, "");
2010
+ const controller = new AbortController();
2011
+ const forwardAbort = () => controller.abort(signal?.reason);
2012
+ signal?.addEventListener("abort", forwardAbort, { once: true });
2013
+ if (signal?.aborted) forwardAbort();
2014
+ const timer = setTimeout(() => controller.abort(new Error("Resource request timed out")), RESOURCE_TIMEOUT_MS);
2015
+ try {
2016
+ controller.signal.throwIfAborted();
2017
+ const family = isIP(hostname);
2018
+ const answers = family ? [{ address: hostname, family }] : await abortable(dnsLookup(hostname, { all: true, verbatim: true }), controller.signal);
2019
+ controller.signal.throwIfAborted();
2020
+ const answer = answers.find((candidate) => isPublicResourceAddress(candidate.address));
2021
+ if (!answer) throw new Error("Resource destination resolved to a blocked address");
2022
+ const transport = url.protocol === "https:" ? httpsRequest : httpRequest;
2023
+ return await new Promise((resolve2, reject) => {
2024
+ let settled = false;
2025
+ const finish = (error, value) => {
2026
+ if (settled) return;
2027
+ settled = true;
2028
+ controller.signal.removeEventListener("abort", onAbort);
2029
+ if (error) reject(error);
2030
+ else resolve2(value);
2031
+ };
2032
+ const upstream = transport(url, {
2033
+ method: "GET",
2034
+ agent: false,
2035
+ headers: { accept: "*/*", host: url.host },
2036
+ ...family ? {} : { servername: hostname },
2037
+ lookup(_hostname, options, callback) {
2038
+ if (options.all) callback(null, [{ address: answer.address, family: answer.family }]);
2039
+ else callback(null, answer.address, answer.family);
2040
+ }
2041
+ }, (incoming) => {
2042
+ const chunks = [];
2043
+ let size = 0;
2044
+ incoming.on("data", (chunk) => {
2045
+ if (settled) return;
2046
+ size += chunk.byteLength;
2047
+ if (size > RESOURCE_MAX_BYTES) {
2048
+ const error = new Error("Resource exceeds byte limit");
2049
+ finish(error);
2050
+ upstream.destroy(error);
2051
+ } else chunks.push(chunk);
2052
+ });
2053
+ incoming.on("error", (error) => finish(error));
2054
+ incoming.on("end", () => finish(void 0, {
2055
+ status: incoming.statusCode ?? 502,
2056
+ contentType: typeof incoming.headers["content-type"] === "string" ? incoming.headers["content-type"] : "application/octet-stream",
2057
+ body: concatBytes(chunks),
2058
+ ...typeof incoming.headers.location === "string" ? { location: incoming.headers.location } : {}
2059
+ }));
2060
+ });
2061
+ function onAbort() {
2062
+ const error = controller.signal.reason instanceof Error ? controller.signal.reason : new Error("Resource request aborted");
2063
+ finish(error);
2064
+ upstream.destroy(error);
2065
+ }
2066
+ upstream.once("error", (error) => finish(error));
2067
+ controller.signal.addEventListener("abort", onAbort, { once: true });
2068
+ if (controller.signal.aborted) onAbort();
2069
+ else upstream.end();
2070
+ });
2071
+ } finally {
2072
+ clearTimeout(timer);
2073
+ signal?.removeEventListener("abort", forwardAbort);
2074
+ }
2075
+ }
2076
+ function abortable(pending, signal) {
2077
+ return new Promise((resolve2, reject) => {
2078
+ const abort = () => {
2079
+ signal.removeEventListener("abort", abort);
2080
+ reject(signal.reason ?? new Error("Resource request aborted"));
2081
+ };
2082
+ if (signal.aborted) {
2083
+ abort();
2084
+ return;
2085
+ }
2086
+ signal.addEventListener("abort", abort, { once: true });
2087
+ pending.then(resolve2, reject).finally(() => signal.removeEventListener("abort", abort));
2088
+ });
2089
+ }
2090
+ function isPublicResourceAddress(address) {
2091
+ const family = isIP(address);
2092
+ if (family === 4) {
2093
+ const [a, b, c] = address.split(".").map(Number);
2094
+ return a !== 0 && a !== 10 && a !== 127 && a < 224 && !(a === 100 && b >= 64 && b <= 127) && !(a === 169 && b === 254) && !(a === 172 && b >= 16 && b <= 31) && !(a === 192 && (b === 168 || b === 0 && (c === 0 || c === 2) || b === 88 && c === 99)) && !(a === 198 && (b === 18 || b === 19 || b === 51 && c === 100)) && !(a === 203 && b === 0 && c === 113);
2095
+ }
2096
+ if (family !== 6) return false;
2097
+ let canonical;
2098
+ try {
2099
+ canonical = new URL(`http://[${address}]/`).hostname.slice(1, -1);
2100
+ } catch {
2101
+ return false;
2102
+ }
2103
+ const [first, second = "0"] = canonical.split(":");
2104
+ const high = Number.parseInt(first, 16);
2105
+ const next = Number.parseInt(second || "0", 16);
2106
+ return high >= 8192 && high <= 16383 && !(high === 8193 && (next < 512 || next === 3512)) && high !== 8194 && !(high === 16383 && next < 4096);
2107
+ }
2108
+ function concatBytes(chunks) {
2109
+ const length = chunks.reduce((total, chunk) => total + chunk.byteLength, 0);
2110
+ const result = new Uint8Array(length);
2111
+ let offset = 0;
2112
+ for (const chunk of chunks) {
2113
+ result.set(chunk, offset);
2114
+ offset += chunk.byteLength;
2115
+ }
2116
+ return result;
2117
+ }
2118
+
2119
+ // src/server.ts
2120
+ import { randomBytes } from "crypto";
1976
2121
  import { readFileSync as readFileSync2 } from "fs";
1977
2122
 
1978
2123
  // src/target-cors.ts
@@ -2036,6 +2181,8 @@ async function startPajaServer(input) {
2036
2181
  let html = renderPajaHtml(hostConfig);
2037
2182
  let configJson = JSON.stringify(hostConfig, null, 2);
2038
2183
  let currentOptions = options;
2184
+ const resourceCapability = randomBytes(32).toString("base64url");
2185
+ let expectedOrigin = "";
2039
2186
  const setHostConfig = (nextOptions) => {
2040
2187
  currentOptions = nextOptions;
2041
2188
  hostConfig = createPajaHostConfig(currentOptions, createdAt);
@@ -2043,9 +2190,18 @@ async function startPajaServer(input) {
2043
2190
  configJson = JSON.stringify(hostConfig, null, 2);
2044
2191
  return hostConfig;
2045
2192
  };
2046
- const handleRequest = async (requestUrl, response) => {
2193
+ const handleRequest = async (request, response) => {
2194
+ const requestUrl = request.url ?? "/";
2195
+ if ((requestUrl === "/" || requestUrl.startsWith("/?") || requestUrl === "/__kehto/target.html") && request.headers.host !== new URL(expectedOrigin).host) {
2196
+ response.writeHead(307, { location: `${expectedOrigin}${requestUrl}`, "cache-control": "no-store" });
2197
+ response.end();
2198
+ return;
2199
+ }
2047
2200
  if (requestUrl === "/" || requestUrl.startsWith("/?")) {
2048
- response.writeHead(200, { "content-type": "text/html; charset=utf-8" });
2201
+ response.writeHead(200, {
2202
+ "content-type": "text/html; charset=utf-8",
2203
+ "set-cookie": `kehto-resource-${new URL(expectedOrigin).port}=${resourceCapability}; Path=/__kehto/resource; HttpOnly; SameSite=Strict`
2204
+ });
2049
2205
  response.end(html);
2050
2206
  return;
2051
2207
  }
@@ -2078,11 +2234,15 @@ async function startPajaServer(input) {
2078
2234
  response.end(browserScript);
2079
2235
  return;
2080
2236
  }
2237
+ if (requestUrl === "/__kehto/resource") {
2238
+ await handleResourceProxy(request, response, expectedOrigin, resourceCapability);
2239
+ return;
2240
+ }
2081
2241
  response.writeHead(404, { "content-type": "text/plain; charset=utf-8" });
2082
2242
  response.end("Not found");
2083
2243
  };
2084
2244
  const server = createServer((request, response) => {
2085
- void handleRequest(request.url ?? "/", response).catch((error) => {
2245
+ void handleRequest(request, response).catch((error) => {
2086
2246
  const message = error instanceof Error ? error.message : String(error);
2087
2247
  response.writeHead(502, { "content-type": "text/plain; charset=utf-8" });
2088
2248
  response.end(message);
@@ -2091,6 +2251,7 @@ async function startPajaServer(input) {
2091
2251
  await listen(server, options.host, options.port);
2092
2252
  const servedOptions = withBoundPort(options, getBoundPort(server, options.port));
2093
2253
  setHostConfig(servedOptions);
2254
+ expectedOrigin = formatPajaUrl(servedOptions).replace(/\/$/u, "");
2094
2255
  return {
2095
2256
  url: formatPajaUrl(servedOptions),
2096
2257
  get hostConfig() {
@@ -2165,6 +2326,94 @@ function normalizeServerTargetUrl(value) {
2165
2326
  }
2166
2327
  return parsed.href;
2167
2328
  }
2329
+ async function handleResourceProxy(request, response, expectedOrigin, capability) {
2330
+ if (request.method !== "POST" || request.headers.origin !== expectedOrigin || request.headers.host !== new URL(expectedOrigin).host || request.headers["content-type"] !== "application/json" || !hasCapability(request.headers.cookie, capability, new URL(expectedOrigin).port)) {
2331
+ response.writeHead(403, { "content-type": "text/plain; charset=utf-8" });
2332
+ response.end("Forbidden");
2333
+ return;
2334
+ }
2335
+ const payload = await readJsonBody(request);
2336
+ if (!payload || typeof payload.url !== "string") {
2337
+ response.writeHead(400, { "content-type": "text/plain; charset=utf-8" });
2338
+ response.end("Invalid resource request");
2339
+ return;
2340
+ }
2341
+ let url;
2342
+ try {
2343
+ url = new URL(payload.url);
2344
+ if (url.protocol !== "http:" && url.protocol !== "https:" || url.username || url.password) throw new Error();
2345
+ } catch {
2346
+ response.writeHead(400, { "content-type": "text/plain; charset=utf-8" });
2347
+ response.end("Invalid resource URL");
2348
+ return;
2349
+ }
2350
+ const controller = new AbortController();
2351
+ response.on("close", () => {
2352
+ if (!response.writableEnded) controller.abort();
2353
+ });
2354
+ try {
2355
+ const upstream = await fetchPinnedResource(url, controller.signal);
2356
+ if (controller.signal.aborted) return;
2357
+ if ([301, 302, 303, 307, 308].includes(upstream.status)) {
2358
+ response.writeHead(200, {
2359
+ "cache-control": "no-store",
2360
+ "content-type": "application/json",
2361
+ "x-kehto-resource-redirect": "1"
2362
+ });
2363
+ response.end(JSON.stringify({ status: upstream.status, location: upstream.location ?? "" }));
2364
+ return;
2365
+ }
2366
+ response.writeHead(upstream.status, {
2367
+ "cache-control": "no-store",
2368
+ "content-type": upstream.contentType,
2369
+ "content-length": String(upstream.body.byteLength)
2370
+ });
2371
+ response.end(upstream.body);
2372
+ } catch (error) {
2373
+ if (controller.signal.aborted) return;
2374
+ const message = error instanceof Error ? error.message : "Resource proxy failed";
2375
+ response.writeHead(502, { "content-type": "text/plain; charset=utf-8" });
2376
+ response.end(message);
2377
+ }
2378
+ }
2379
+ function hasCapability(header, capability, port) {
2380
+ if (typeof header !== "string") return false;
2381
+ return header.split(";").some((part) => part.trim() === `kehto-resource-${port}=${capability}`);
2382
+ }
2383
+ function readJsonBody(request) {
2384
+ return new Promise((resolve2) => {
2385
+ const chunks = [];
2386
+ let size = 0;
2387
+ let settled = false;
2388
+ const finish = (value) => {
2389
+ if (settled) return;
2390
+ settled = true;
2391
+ clearTimeout(timer);
2392
+ resolve2(value);
2393
+ };
2394
+ const timer = setTimeout(() => {
2395
+ finish(null);
2396
+ request.destroy();
2397
+ }, 1e4);
2398
+ request.on("data", (chunk) => {
2399
+ if (settled) return;
2400
+ size += chunk.byteLength;
2401
+ if (size > 4096) {
2402
+ finish(null);
2403
+ request.destroy();
2404
+ } else chunks.push(chunk);
2405
+ });
2406
+ request.on("aborted", () => finish(null));
2407
+ request.on("error", () => finish(null));
2408
+ request.on("end", () => {
2409
+ try {
2410
+ finish(JSON.parse(new TextDecoder().decode(concatBytes(chunks))));
2411
+ } catch {
2412
+ finish(null);
2413
+ }
2414
+ });
2415
+ });
2416
+ }
2168
2417
 
2169
2418
  // src/browser-llm-connections.ts
2170
2419
  import {
@@ -2649,4 +2898,4 @@ export {
2649
2898
  validatePajaLlmVaultPassword,
2650
2899
  createPajaLlmVault
2651
2900
  };
2652
- //# sourceMappingURL=chunk-DDYBKY5L.js.map
2901
+ //# sourceMappingURL=chunk-IWFPIHAE.js.map