@kehto/paja 0.32.1 → 0.33.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.
@@ -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;
@@ -1698,6 +1710,7 @@ var BrowserIntentController = class {
1698
1710
  /** Complete an already accepted delivery. Kept public for host diagnostics and tests. */
1699
1711
  async dispatch(params) {
1700
1712
  const dispatch = freezeDispatch(params);
1713
+ if (dispatch.signal?.aborted) throw new Error("intent target cancelled");
1701
1714
  let reason = "no-current-target";
1702
1715
  for (let attempt = 1; attempt <= this.maxAttempts; attempt += 1) {
1703
1716
  let generation;
@@ -1717,6 +1730,7 @@ var BrowserIntentController = class {
1717
1730
  reason = "ready-failed";
1718
1731
  continue;
1719
1732
  }
1733
+ if (dispatch.signal?.aborted) throw new Error("intent target cancelled");
1720
1734
  if (!await this.options.isCurrent(generation)) {
1721
1735
  reason = "no-current-target";
1722
1736
  continue;
@@ -1756,7 +1770,8 @@ function freezeDispatch(params) {
1756
1770
  convention: params.convention,
1757
1771
  ...params.payload === void 0 ? {} : { payload },
1758
1772
  ...behavior === void 0 ? {} : { behavior },
1759
- ...params.sourceWindowId === void 0 ? {} : { sourceWindowId: params.sourceWindowId }
1773
+ ...params.sourceWindowId === void 0 ? {} : { sourceWindowId: params.sourceWindowId },
1774
+ ...params.signal === void 0 ? {} : { signal: params.signal }
1760
1775
  });
1761
1776
  }
1762
1777
  function freezeValue(value, seen = /* @__PURE__ */ new WeakMap()) {
@@ -1973,6 +1988,131 @@ function postPajaIntentLauncherMessage(frame, message) {
1973
1988
 
1974
1989
  // src/server.ts
1975
1990
  import { createServer } from "http";
1991
+
1992
+ // src/server-resource-transport.ts
1993
+ import { request as httpRequest } from "http";
1994
+ import { request as httpsRequest } from "https";
1995
+ import { lookup as dnsLookup } from "dns/promises";
1996
+ import { isIP } from "net";
1997
+ var RESOURCE_MAX_BYTES = 10 * 1024 * 1024;
1998
+ var RESOURCE_TIMEOUT_MS = 3e4;
1999
+ async function fetchPinnedResource(input, signal) {
2000
+ const url = new URL(input.href);
2001
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password) {
2002
+ throw new Error("Invalid resource URL");
2003
+ }
2004
+ const hostname = url.hostname.replace(/^\[|\]$/gu, "");
2005
+ const controller = new AbortController();
2006
+ const forwardAbort = () => controller.abort(signal?.reason);
2007
+ signal?.addEventListener("abort", forwardAbort, { once: true });
2008
+ if (signal?.aborted) forwardAbort();
2009
+ const timer = setTimeout(() => controller.abort(new Error("Resource request timed out")), RESOURCE_TIMEOUT_MS);
2010
+ try {
2011
+ controller.signal.throwIfAborted();
2012
+ const family = isIP(hostname);
2013
+ const answers = family ? [{ address: hostname, family }] : await abortable(dnsLookup(hostname, { all: true, verbatim: true }), controller.signal);
2014
+ controller.signal.throwIfAborted();
2015
+ const answer = answers.find((candidate) => isPublicResourceAddress(candidate.address));
2016
+ if (!answer) throw new Error("Resource destination resolved to a blocked address");
2017
+ const transport = url.protocol === "https:" ? httpsRequest : httpRequest;
2018
+ return await new Promise((resolve2, reject) => {
2019
+ let settled = false;
2020
+ const finish = (error, value) => {
2021
+ if (settled) return;
2022
+ settled = true;
2023
+ controller.signal.removeEventListener("abort", onAbort);
2024
+ if (error) reject(error);
2025
+ else resolve2(value);
2026
+ };
2027
+ const upstream = transport(url, {
2028
+ method: "GET",
2029
+ agent: false,
2030
+ headers: { accept: "*/*", host: url.host },
2031
+ ...family ? {} : { servername: hostname },
2032
+ lookup(_hostname, options, callback) {
2033
+ if (options.all) callback(null, [{ address: answer.address, family: answer.family }]);
2034
+ else callback(null, answer.address, answer.family);
2035
+ }
2036
+ }, (incoming) => {
2037
+ const chunks = [];
2038
+ let size = 0;
2039
+ incoming.on("data", (chunk) => {
2040
+ if (settled) return;
2041
+ size += chunk.byteLength;
2042
+ if (size > RESOURCE_MAX_BYTES) {
2043
+ const error = new Error("Resource exceeds byte limit");
2044
+ finish(error);
2045
+ upstream.destroy(error);
2046
+ } else chunks.push(chunk);
2047
+ });
2048
+ incoming.on("error", (error) => finish(error));
2049
+ incoming.on("end", () => finish(void 0, {
2050
+ status: incoming.statusCode ?? 502,
2051
+ contentType: typeof incoming.headers["content-type"] === "string" ? incoming.headers["content-type"] : "application/octet-stream",
2052
+ body: concatBytes(chunks),
2053
+ ...typeof incoming.headers.location === "string" ? { location: incoming.headers.location } : {}
2054
+ }));
2055
+ });
2056
+ function onAbort() {
2057
+ const error = controller.signal.reason instanceof Error ? controller.signal.reason : new Error("Resource request aborted");
2058
+ finish(error);
2059
+ upstream.destroy(error);
2060
+ }
2061
+ upstream.once("error", (error) => finish(error));
2062
+ controller.signal.addEventListener("abort", onAbort, { once: true });
2063
+ if (controller.signal.aborted) onAbort();
2064
+ else upstream.end();
2065
+ });
2066
+ } finally {
2067
+ clearTimeout(timer);
2068
+ signal?.removeEventListener("abort", forwardAbort);
2069
+ }
2070
+ }
2071
+ function abortable(pending, signal) {
2072
+ return new Promise((resolve2, reject) => {
2073
+ const abort = () => {
2074
+ signal.removeEventListener("abort", abort);
2075
+ reject(signal.reason ?? new Error("Resource request aborted"));
2076
+ };
2077
+ if (signal.aborted) {
2078
+ abort();
2079
+ return;
2080
+ }
2081
+ signal.addEventListener("abort", abort, { once: true });
2082
+ pending.then(resolve2, reject).finally(() => signal.removeEventListener("abort", abort));
2083
+ });
2084
+ }
2085
+ function isPublicResourceAddress(address) {
2086
+ const family = isIP(address);
2087
+ if (family === 4) {
2088
+ const [a, b, c] = address.split(".").map(Number);
2089
+ 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);
2090
+ }
2091
+ if (family !== 6) return false;
2092
+ let canonical;
2093
+ try {
2094
+ canonical = new URL(`http://[${address}]/`).hostname.slice(1, -1);
2095
+ } catch {
2096
+ return false;
2097
+ }
2098
+ const [first, second = "0"] = canonical.split(":");
2099
+ const high = Number.parseInt(first, 16);
2100
+ const next = Number.parseInt(second || "0", 16);
2101
+ return high >= 8192 && high <= 16383 && !(high === 8193 && (next < 512 || next === 3512)) && high !== 8194 && !(high === 16383 && next < 4096);
2102
+ }
2103
+ function concatBytes(chunks) {
2104
+ const length = chunks.reduce((total, chunk) => total + chunk.byteLength, 0);
2105
+ const result = new Uint8Array(length);
2106
+ let offset = 0;
2107
+ for (const chunk of chunks) {
2108
+ result.set(chunk, offset);
2109
+ offset += chunk.byteLength;
2110
+ }
2111
+ return result;
2112
+ }
2113
+
2114
+ // src/server.ts
2115
+ import { randomBytes } from "crypto";
1976
2116
  import { readFileSync as readFileSync2 } from "fs";
1977
2117
 
1978
2118
  // src/target-cors.ts
@@ -2036,6 +2176,8 @@ async function startPajaServer(input) {
2036
2176
  let html = renderPajaHtml(hostConfig);
2037
2177
  let configJson = JSON.stringify(hostConfig, null, 2);
2038
2178
  let currentOptions = options;
2179
+ const resourceCapability = randomBytes(32).toString("base64url");
2180
+ let expectedOrigin = "";
2039
2181
  const setHostConfig = (nextOptions) => {
2040
2182
  currentOptions = nextOptions;
2041
2183
  hostConfig = createPajaHostConfig(currentOptions, createdAt);
@@ -2043,9 +2185,18 @@ async function startPajaServer(input) {
2043
2185
  configJson = JSON.stringify(hostConfig, null, 2);
2044
2186
  return hostConfig;
2045
2187
  };
2046
- const handleRequest = async (requestUrl, response) => {
2188
+ const handleRequest = async (request, response) => {
2189
+ const requestUrl = request.url ?? "/";
2190
+ if ((requestUrl === "/" || requestUrl.startsWith("/?") || requestUrl === "/__kehto/target.html") && request.headers.host !== new URL(expectedOrigin).host) {
2191
+ response.writeHead(307, { location: `${expectedOrigin}${requestUrl}`, "cache-control": "no-store" });
2192
+ response.end();
2193
+ return;
2194
+ }
2047
2195
  if (requestUrl === "/" || requestUrl.startsWith("/?")) {
2048
- response.writeHead(200, { "content-type": "text/html; charset=utf-8" });
2196
+ response.writeHead(200, {
2197
+ "content-type": "text/html; charset=utf-8",
2198
+ "set-cookie": `kehto-resource-${new URL(expectedOrigin).port}=${resourceCapability}; Path=/__kehto/resource; HttpOnly; SameSite=Strict`
2199
+ });
2049
2200
  response.end(html);
2050
2201
  return;
2051
2202
  }
@@ -2078,11 +2229,15 @@ async function startPajaServer(input) {
2078
2229
  response.end(browserScript);
2079
2230
  return;
2080
2231
  }
2232
+ if (requestUrl === "/__kehto/resource") {
2233
+ await handleResourceProxy(request, response, expectedOrigin, resourceCapability);
2234
+ return;
2235
+ }
2081
2236
  response.writeHead(404, { "content-type": "text/plain; charset=utf-8" });
2082
2237
  response.end("Not found");
2083
2238
  };
2084
2239
  const server = createServer((request, response) => {
2085
- void handleRequest(request.url ?? "/", response).catch((error) => {
2240
+ void handleRequest(request, response).catch((error) => {
2086
2241
  const message = error instanceof Error ? error.message : String(error);
2087
2242
  response.writeHead(502, { "content-type": "text/plain; charset=utf-8" });
2088
2243
  response.end(message);
@@ -2091,6 +2246,7 @@ async function startPajaServer(input) {
2091
2246
  await listen(server, options.host, options.port);
2092
2247
  const servedOptions = withBoundPort(options, getBoundPort(server, options.port));
2093
2248
  setHostConfig(servedOptions);
2249
+ expectedOrigin = formatPajaUrl(servedOptions).replace(/\/$/u, "");
2094
2250
  return {
2095
2251
  url: formatPajaUrl(servedOptions),
2096
2252
  get hostConfig() {
@@ -2165,6 +2321,94 @@ function normalizeServerTargetUrl(value) {
2165
2321
  }
2166
2322
  return parsed.href;
2167
2323
  }
2324
+ async function handleResourceProxy(request, response, expectedOrigin, capability) {
2325
+ 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)) {
2326
+ response.writeHead(403, { "content-type": "text/plain; charset=utf-8" });
2327
+ response.end("Forbidden");
2328
+ return;
2329
+ }
2330
+ const payload = await readJsonBody(request);
2331
+ if (!payload || typeof payload.url !== "string") {
2332
+ response.writeHead(400, { "content-type": "text/plain; charset=utf-8" });
2333
+ response.end("Invalid resource request");
2334
+ return;
2335
+ }
2336
+ let url;
2337
+ try {
2338
+ url = new URL(payload.url);
2339
+ if (url.protocol !== "http:" && url.protocol !== "https:" || url.username || url.password) throw new Error();
2340
+ } catch {
2341
+ response.writeHead(400, { "content-type": "text/plain; charset=utf-8" });
2342
+ response.end("Invalid resource URL");
2343
+ return;
2344
+ }
2345
+ const controller = new AbortController();
2346
+ response.on("close", () => {
2347
+ if (!response.writableEnded) controller.abort();
2348
+ });
2349
+ try {
2350
+ const upstream = await fetchPinnedResource(url, controller.signal);
2351
+ if (controller.signal.aborted) return;
2352
+ if ([301, 302, 303, 307, 308].includes(upstream.status)) {
2353
+ response.writeHead(200, {
2354
+ "cache-control": "no-store",
2355
+ "content-type": "application/json",
2356
+ "x-kehto-resource-redirect": "1"
2357
+ });
2358
+ response.end(JSON.stringify({ status: upstream.status, location: upstream.location ?? "" }));
2359
+ return;
2360
+ }
2361
+ response.writeHead(upstream.status, {
2362
+ "cache-control": "no-store",
2363
+ "content-type": upstream.contentType,
2364
+ "content-length": String(upstream.body.byteLength)
2365
+ });
2366
+ response.end(upstream.body);
2367
+ } catch (error) {
2368
+ if (controller.signal.aborted) return;
2369
+ const message = error instanceof Error ? error.message : "Resource proxy failed";
2370
+ response.writeHead(502, { "content-type": "text/plain; charset=utf-8" });
2371
+ response.end(message);
2372
+ }
2373
+ }
2374
+ function hasCapability(header, capability, port) {
2375
+ if (typeof header !== "string") return false;
2376
+ return header.split(";").some((part) => part.trim() === `kehto-resource-${port}=${capability}`);
2377
+ }
2378
+ function readJsonBody(request) {
2379
+ return new Promise((resolve2) => {
2380
+ const chunks = [];
2381
+ let size = 0;
2382
+ let settled = false;
2383
+ const finish = (value) => {
2384
+ if (settled) return;
2385
+ settled = true;
2386
+ clearTimeout(timer);
2387
+ resolve2(value);
2388
+ };
2389
+ const timer = setTimeout(() => {
2390
+ finish(null);
2391
+ request.destroy();
2392
+ }, 1e4);
2393
+ request.on("data", (chunk) => {
2394
+ if (settled) return;
2395
+ size += chunk.byteLength;
2396
+ if (size > 4096) {
2397
+ finish(null);
2398
+ request.destroy();
2399
+ } else chunks.push(chunk);
2400
+ });
2401
+ request.on("aborted", () => finish(null));
2402
+ request.on("error", () => finish(null));
2403
+ request.on("end", () => {
2404
+ try {
2405
+ finish(JSON.parse(new TextDecoder().decode(concatBytes(chunks))));
2406
+ } catch {
2407
+ finish(null);
2408
+ }
2409
+ });
2410
+ });
2411
+ }
2168
2412
 
2169
2413
  // src/browser-llm-connections.ts
2170
2414
  import {
@@ -2649,4 +2893,4 @@ export {
2649
2893
  validatePajaLlmVaultPassword,
2650
2894
  createPajaLlmVault
2651
2895
  };
2652
- //# sourceMappingURL=chunk-DDYBKY5L.js.map
2896
+ //# sourceMappingURL=chunk-ZAIBJIBA.js.map