@kehto/paja 0.29.0 → 0.31.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.
@@ -14138,8 +14138,9 @@ async function* readLlmSseData(body, signal) {
14138
14138
  var PRESET_ROWS = [
14139
14139
  { id: "openai", label: "OpenAI", protocol: "openai-chat", baseUrl: "https://api.openai.com/v1", requiresCredential: true, local: false, docsUrl: "https://platform.openai.com/docs/api-reference/chat", exampleModels: ["gpt-4.1-mini", "gpt-4o-mini"] },
14140
14140
  { id: "anthropic", label: "Anthropic", protocol: "anthropic-messages", baseUrl: "https://api.anthropic.com/v1", requiresCredential: true, local: false, docsUrl: "https://docs.anthropic.com/en/api/messages", exampleModels: ["claude-sonnet-4-5", "claude-haiku-4-5"] },
14141
- { id: "gemini", label: "Google Gemini", protocol: "gemini", baseUrl: "https://generativelanguage.googleapis.com/v1beta", requiresCredential: true, local: false, docsUrl: "https://ai.google.dev/api/generate-content", exampleModels: ["gemini-2.5-flash", "gemini-2.5-pro"] },
14142
14141
  { id: "openrouter", label: "OpenRouter", protocol: "openai-chat", baseUrl: "https://openrouter.ai/api/v1", requiresCredential: true, local: false, docsUrl: "https://openrouter.ai/docs/api-reference/overview", exampleModels: ["openai/gpt-4.1-mini", "anthropic/claude-sonnet-4.5"] },
14142
+ { id: "routstr", label: "Routstr", protocol: "openai-chat", baseUrl: "http://127.0.0.1:8008/v1", requiresCredential: false, local: true, docsUrl: "https://routstr.com", exampleModels: [], modelsPath: "/models" },
14143
+ { id: "gemini", label: "Google Gemini", protocol: "gemini", baseUrl: "https://generativelanguage.googleapis.com/v1beta", requiresCredential: true, local: false, docsUrl: "https://ai.google.dev/api/generate-content", exampleModels: ["gemini-2.5-flash", "gemini-2.5-pro"] },
14143
14144
  { id: "groq", label: "Groq", protocol: "openai-chat", baseUrl: "https://api.groq.com/openai/v1", requiresCredential: true, local: false, docsUrl: "https://console.groq.com/docs/openai", exampleModels: ["llama-3.3-70b-versatile"] },
14144
14145
  { id: "mistral", label: "Mistral", protocol: "openai-chat", baseUrl: "https://api.mistral.ai/v1", requiresCredential: true, local: false, docsUrl: "https://docs.mistral.ai/api/", exampleModels: ["mistral-small-latest"] },
14145
14146
  { id: "deepseek", label: "DeepSeek", protocol: "openai-chat", baseUrl: "https://api.deepseek.com/v1", requiresCredential: true, local: false, docsUrl: "https://api-docs.deepseek.com/", exampleModels: ["deepseek-chat"] },
@@ -14786,6 +14787,136 @@ function installPajaResourceSettings() {
14786
14787
  return { getServers: settings.getServers, dispose: () => form?.removeEventListener("submit", submit) };
14787
14788
  }
14788
14789
 
14790
+ // src/browser-security-settings.ts
14791
+ var STORAGE_KEY2 = "kehto:paja:nested-context-lock";
14792
+ function isSetting(value) {
14793
+ return value === "auto" || value === "on" || value === "off";
14794
+ }
14795
+ function readStoredNestedContextLockSetting(getStorage = () => localStorage) {
14796
+ try {
14797
+ const stored = getStorage().getItem(STORAGE_KEY2);
14798
+ return isSetting(stored) ? stored : null;
14799
+ } catch {
14800
+ return null;
14801
+ }
14802
+ }
14803
+ function createPajaSecuritySettings(getStorage = () => localStorage) {
14804
+ let setting = readStoredNestedContextLockSetting(getStorage);
14805
+ let status = setting ? `Frame-creation lock forced ${setting} for this host.` : "Frame-creation lock follows the host default.";
14806
+ return {
14807
+ getSetting: () => setting,
14808
+ getStatus: () => status,
14809
+ save(next) {
14810
+ if (next !== "" && !isSetting(next)) {
14811
+ return { ok: false, message: "Choose host default, auto, on, or off." };
14812
+ }
14813
+ try {
14814
+ const storage = getStorage();
14815
+ if (next === "") {
14816
+ storage.removeItem(STORAGE_KEY2);
14817
+ setting = null;
14818
+ status = "Frame-creation lock follows the host default.";
14819
+ } else {
14820
+ storage.setItem(STORAGE_KEY2, next);
14821
+ setting = next;
14822
+ status = `Frame-creation lock forced ${next}; applies on the next napplet load.`;
14823
+ }
14824
+ } catch {
14825
+ setting = next === "" ? null : next;
14826
+ status = "Applied for this session only; storage is unavailable, so the choice will not persist.";
14827
+ }
14828
+ return { ok: true, message: status };
14829
+ }
14830
+ };
14831
+ }
14832
+ function installPajaSecuritySettings() {
14833
+ const settings = createPajaSecuritySettings();
14834
+ const select2 = document.getElementById("paja-nested-context-lock");
14835
+ const status = document.getElementById("paja-nested-context-lock-status");
14836
+ if (!select2 || !status) return { getSetting: settings.getSetting, dispose: () => {
14837
+ } };
14838
+ select2.value = settings.getSetting() ?? "";
14839
+ status.textContent = settings.getStatus();
14840
+ const onChange = () => {
14841
+ const result2 = settings.save(select2.value);
14842
+ select2.setAttribute("aria-invalid", String(!result2.ok));
14843
+ status.textContent = result2.message;
14844
+ if (!result2.ok) select2.value = settings.getSetting() ?? "";
14845
+ };
14846
+ select2.addEventListener("change", onChange);
14847
+ return { getSetting: settings.getSetting, dispose: () => select2.removeEventListener("change", onChange) };
14848
+ }
14849
+
14850
+ // src/browser-llm-models.ts
14851
+ var PajaLlmModelsError = class extends Error {
14852
+ constructor(failure4, message3) {
14853
+ super(message3);
14854
+ this.failure = failure4;
14855
+ this.name = "PajaLlmModelsError";
14856
+ }
14857
+ failure;
14858
+ };
14859
+ var PAJA_LLM_MODELS_TIMEOUT_MS = 8e3;
14860
+ function llmModelsUrl(baseUrl, modelsPath) {
14861
+ return `${baseUrl.trim().replace(/\/+$/, "")}/${modelsPath.trim().replace(/^\/+/, "")}`;
14862
+ }
14863
+ function readModelIds(body) {
14864
+ const rows = Array.isArray(body) ? body : body && typeof body === "object" ? body.data ?? body.models : void 0;
14865
+ if (!Array.isArray(rows)) throw new PajaLlmModelsError("shape", "The server did not return a model list.");
14866
+ const ids = [];
14867
+ const seen = /* @__PURE__ */ new Set();
14868
+ for (const row of rows) {
14869
+ const id = typeof row === "string" ? row : row && typeof row === "object" && typeof row.id === "string" ? row.id : void 0;
14870
+ const trimmed = id?.trim();
14871
+ if (!trimmed || seen.has(trimmed)) continue;
14872
+ seen.add(trimmed);
14873
+ ids.push(trimmed);
14874
+ }
14875
+ if (ids.length === 0) throw new PajaLlmModelsError("shape", "The server reported no models.");
14876
+ return ids.sort((a, b) => a.localeCompare(b));
14877
+ }
14878
+ async function fetchPajaLlmModels(options) {
14879
+ const fetchImpl = options.fetch ?? globalThis.fetch;
14880
+ const controller = new AbortController();
14881
+ const timeoutMs = options.timeoutMs ?? PAJA_LLM_MODELS_TIMEOUT_MS;
14882
+ let timedOut = false;
14883
+ const timer = setTimeout(() => {
14884
+ timedOut = true;
14885
+ controller.abort();
14886
+ }, timeoutMs);
14887
+ const abortFromCaller = () => controller.abort();
14888
+ options.signal?.addEventListener("abort", abortFromCaller, { once: true });
14889
+ const reason = () => timedOut ? "timeout" : options.signal?.aborted ? "aborted" : "network";
14890
+ try {
14891
+ const headers = { accept: "application/json" };
14892
+ if (options.credential) headers.authorization = `Bearer ${options.credential}`;
14893
+ const response = await fetchImpl(llmModelsUrl(options.baseUrl, options.modelsPath), {
14894
+ method: "GET",
14895
+ headers,
14896
+ signal: controller.signal
14897
+ });
14898
+ if (!response.ok) {
14899
+ throw new PajaLlmModelsError("http", `The server answered ${String(response.status)} for ${options.modelsPath}.`);
14900
+ }
14901
+ let body;
14902
+ try {
14903
+ body = await response.json();
14904
+ } catch {
14905
+ throw new PajaLlmModelsError("shape", "The server did not return JSON for the model list.");
14906
+ }
14907
+ return readModelIds(body);
14908
+ } catch (error) {
14909
+ if (error instanceof PajaLlmModelsError) throw error;
14910
+ if (timedOut || options.signal?.aborted) {
14911
+ throw new PajaLlmModelsError(reason(), timedOut ? `No answer from the server within ${String(Math.round(timeoutMs / 1e3))}s.` : "The model listing was cancelled.");
14912
+ }
14913
+ throw new PajaLlmModelsError("network", "Could not read the model list \u2014 the server is down, or it does not allow this page cross-origin (CORS).");
14914
+ } finally {
14915
+ clearTimeout(timer);
14916
+ options.signal?.removeEventListener("abort", abortFromCaller);
14917
+ }
14918
+ }
14919
+
14789
14920
  // src/browser-llm-connections.ts
14790
14921
  var PAJA_LLM_CONNECTIONS_STORAGE_KEY = "kehto:paja:llm-connections:v1";
14791
14922
  var MAX_CONNECTIONS = 32;
@@ -15308,6 +15439,10 @@ function readForm() {
15308
15439
  const name = byId("paja-llm-name", HTMLInputElement);
15309
15440
  const baseUrl = byId("paja-llm-base-url", HTMLInputElement);
15310
15441
  const model = byId("paja-llm-model", HTMLInputElement);
15442
+ const modelField = byId("paja-llm-model-field", HTMLElement);
15443
+ const modelSelect = byId("paja-llm-model-select", HTMLSelectElement);
15444
+ const modelSelectField = byId("paja-llm-model-select-field", HTMLElement);
15445
+ const modelStatus = byId("paja-llm-model-status", HTMLElement);
15311
15446
  const examples = byId("paja-llm-model-examples", HTMLDataListElement);
15312
15447
  const credential = byId("paja-llm-credential", HTMLInputElement);
15313
15448
  const remember = byId("paja-llm-remember", HTMLInputElement);
@@ -15316,8 +15451,27 @@ function readForm() {
15316
15451
  const list = byId("paja-llm-connections", HTMLElement);
15317
15452
  const status = byId("paja-llm-status", HTMLElement);
15318
15453
  const lock = byId("paja-llm-vault-lock", HTMLButtonElement);
15319
- if (!form || !preset || !name || !baseUrl || !model || !examples || !credential || !remember || !images || !json || !list || !status || !lock) return null;
15320
- return { form, preset, name, baseUrl, model, examples, credential, remember, images, json, list, status, lock, section: byId("paja-section-llm", HTMLDetailsElement) };
15454
+ if (!form || !preset || !name || !baseUrl || !model || !modelField || !modelSelect || !modelSelectField || !modelStatus || !examples || !credential || !remember || !images || !json || !list || !status || !lock) return null;
15455
+ return {
15456
+ form,
15457
+ preset,
15458
+ name,
15459
+ baseUrl,
15460
+ model,
15461
+ modelField,
15462
+ modelSelect,
15463
+ modelSelectField,
15464
+ modelStatus,
15465
+ examples,
15466
+ credential,
15467
+ remember,
15468
+ images,
15469
+ json,
15470
+ list,
15471
+ status,
15472
+ lock,
15473
+ section: byId("paja-section-llm", HTMLDetailsElement)
15474
+ };
15321
15475
  }
15322
15476
  function installPajaLlmPanel(options) {
15323
15477
  const { store: store2, vault } = options;
@@ -15350,14 +15504,89 @@ function installPajaLlmPanel(options) {
15350
15504
  setStatus2("Wrong vault password. Try again or clear the vault to start over.", true);
15351
15505
  }
15352
15506
  }
15507
+ let modelListing = null;
15508
+ function setModelStatus(text2, state = "idle") {
15509
+ if (!elements) return;
15510
+ elements.modelStatus.textContent = text2;
15511
+ if (state === "idle") delete elements.modelStatus.dataset.state;
15512
+ else elements.modelStatus.dataset.state = state;
15513
+ }
15514
+ function setModelMode(mode) {
15515
+ if (!elements) return;
15516
+ const listing = mode === "select";
15517
+ elements.modelField.hidden = listing;
15518
+ elements.modelSelectField.hidden = !listing;
15519
+ elements.model.disabled = listing;
15520
+ elements.modelSelect.disabled = !listing;
15521
+ }
15522
+ function currentModel() {
15523
+ if (!elements) return "";
15524
+ return (elements.modelSelectField.hidden ? elements.model.value : elements.modelSelect.value).trim();
15525
+ }
15526
+ async function refreshModels() {
15527
+ if (!elements) return;
15528
+ modelListing?.abort();
15529
+ modelListing = null;
15530
+ const preset = presetById(elements.preset.value);
15531
+ const modelsPath = preset?.modelsPath;
15532
+ if (!modelsPath) {
15533
+ setModelMode("text");
15534
+ setModelStatus("");
15535
+ return;
15536
+ }
15537
+ setModelMode("select");
15538
+ elements.modelSelect.replaceChildren();
15539
+ let baseUrl;
15540
+ try {
15541
+ baseUrl = normalizePajaLlmBaseUrl(elements.baseUrl.value);
15542
+ } catch (error) {
15543
+ setModelMode("text");
15544
+ setModelStatus(error instanceof Error ? error.message : "Enter an absolute API base URL.", "error");
15545
+ return;
15546
+ }
15547
+ const controller = new AbortController();
15548
+ modelListing = controller;
15549
+ setModelStatus("Connecting\u2026", "busy");
15550
+ try {
15551
+ const models = await fetchPajaLlmModels({
15552
+ baseUrl,
15553
+ modelsPath,
15554
+ ...elements.credential.value.trim() ? { credential: elements.credential.value.trim() } : {},
15555
+ signal: controller.signal
15556
+ });
15557
+ if (modelListing !== controller || !elements) return;
15558
+ elements.modelSelect.replaceChildren(...models.map((id) => Object.assign(document.createElement("option"), { value: id, textContent: id })));
15559
+ setModelStatus(`Connected \u2713 \u2014 ${String(models.length)} model${models.length === 1 ? "" : "s"}`, "ready");
15560
+ } catch (error) {
15561
+ if (modelListing !== controller || !elements) return;
15562
+ if (error instanceof PajaLlmModelsError && error.failure === "aborted") return;
15563
+ setModelMode("text");
15564
+ setModelStatus(`${error instanceof Error ? error.message : "Could not list models."} Type the model id instead.`, "error");
15565
+ if (preset.id === "routstr") {
15566
+ const install = Object.assign(document.createElement("a"), {
15567
+ href: "https://routstr.com/routstrd",
15568
+ textContent: "Install routstrd",
15569
+ target: "_blank",
15570
+ rel: "noopener noreferrer"
15571
+ });
15572
+ elements.modelStatus.append(document.createElement("br"), install);
15573
+ }
15574
+ } finally {
15575
+ if (modelListing === controller) modelListing = null;
15576
+ }
15577
+ }
15578
+ let appliedPreset;
15353
15579
  function applyPreset() {
15354
15580
  if (!elements) return;
15355
15581
  const preset = presetById(elements.preset.value);
15356
15582
  if (!preset) return;
15583
+ if (appliedPreset && appliedPreset.id !== preset.id) elements.credential.value = "";
15584
+ if (!elements.name.value || elements.name.value === appliedPreset?.label) elements.name.value = preset.label;
15585
+ appliedPreset = preset;
15357
15586
  if (preset.baseUrl) elements.baseUrl.value = preset.baseUrl;
15358
15587
  elements.examples.replaceChildren(...preset.exampleModels.map((value) => Object.assign(document.createElement("option"), { value })));
15359
- if (!elements.name.value) elements.name.value = preset.label;
15360
15588
  elements.credential.placeholder = preset.requiresCredential ? "API key (sent only to this base URL)" : "Optional for local servers";
15589
+ void refreshModels();
15361
15590
  }
15362
15591
  function renderList() {
15363
15592
  if (!elements) return;
@@ -15403,6 +15632,11 @@ function installPajaLlmPanel(options) {
15403
15632
  const credential = elements.credential.value;
15404
15633
  const storage = credential ? elements.remember.checked ? "vault" : "session" : "none";
15405
15634
  const preset = presetById(elements.preset.value);
15635
+ const model = currentModel();
15636
+ if (!model) {
15637
+ setModelStatus("Choose or type a model id.", "error");
15638
+ return;
15639
+ }
15406
15640
  let record3;
15407
15641
  try {
15408
15642
  record3 = {
@@ -15411,7 +15645,7 @@ function installPajaLlmPanel(options) {
15411
15645
  presetId: preset?.id ?? "custom",
15412
15646
  protocol: preset?.protocol ?? "openai-chat",
15413
15647
  baseUrl: normalizePajaLlmBaseUrl(elements.baseUrl.value),
15414
- model: elements.model.value,
15648
+ model,
15415
15649
  images: elements.images.checked,
15416
15650
  json: elements.json.checked,
15417
15651
  credentialStorage: storage,
@@ -15438,6 +15672,10 @@ function installPajaLlmPanel(options) {
15438
15672
  elements.preset.replaceChildren(...LLM_PROVIDER_PRESETS.map((preset) => Object.assign(document.createElement("option"), { value: preset.id, textContent: preset.label })));
15439
15673
  applyPreset();
15440
15674
  const onPreset = () => applyPreset();
15675
+ const onBaseUrl = () => {
15676
+ if (!presetById(elements.preset.value)?.modelsPath) return;
15677
+ void refreshModels();
15678
+ };
15441
15679
  const onSubmit = (event) => {
15442
15680
  void submit(event);
15443
15681
  };
@@ -15448,10 +15686,13 @@ function installPajaLlmPanel(options) {
15448
15686
  options.onChange?.();
15449
15687
  };
15450
15688
  elements.preset.addEventListener("change", onPreset);
15689
+ elements.baseUrl.addEventListener("change", onBaseUrl);
15451
15690
  elements.form.addEventListener("submit", onSubmit);
15452
15691
  elements.lock.addEventListener("click", onLock);
15453
15692
  disposers.push(() => {
15693
+ modelListing?.abort();
15454
15694
  elements.preset.removeEventListener("change", onPreset);
15695
+ elements.baseUrl.removeEventListener("change", onBaseUrl);
15455
15696
  elements.form.removeEventListener("submit", onSubmit);
15456
15697
  elements.lock.removeEventListener("click", onLock);
15457
15698
  });
@@ -16113,7 +16354,7 @@ var sessionRegistry = {
16113
16354
  }
16114
16355
  };
16115
16356
  var nappKeyRegistry = sessionRegistry;
16116
- var STORAGE_KEY2 = "napplet:acl";
16357
+ var STORAGE_KEY3 = "napplet:acl";
16117
16358
  var DEFAULT_STATE_QUOTA = 512 * 1024;
16118
16359
  function aclKey(_pubkey, dTag, aggregateHash) {
16119
16360
  return `${dTag}:${aggregateHash}`;
@@ -16280,14 +16521,14 @@ var aclStore = {
16280
16521
  stateQuota: val.stateQuota
16281
16522
  }
16282
16523
  ]);
16283
- localStorage.setItem(STORAGE_KEY2, JSON.stringify(entries));
16524
+ localStorage.setItem(STORAGE_KEY3, JSON.stringify(entries));
16284
16525
  } catch {
16285
16526
  }
16286
16527
  },
16287
16528
  /** Load the ACL store from localStorage. Migrates old 3-segment keys to 2-segment format. */
16288
16529
  load() {
16289
16530
  try {
16290
- const raw = localStorage.getItem(STORAGE_KEY2);
16531
+ const raw = localStorage.getItem(STORAGE_KEY3);
16291
16532
  if (!raw) return;
16292
16533
  let entries = JSON.parse(raw);
16293
16534
  const hasOldKeys = entries.some(([key]) => key.split(":").length === 3);
@@ -16315,7 +16556,7 @@ var aclStore = {
16315
16556
  stateQuota: entry.quota
16316
16557
  }];
16317
16558
  });
16318
- localStorage.setItem(STORAGE_KEY2, JSON.stringify(entries));
16559
+ localStorage.setItem(STORAGE_KEY3, JSON.stringify(entries));
16319
16560
  }
16320
16561
  }
16321
16562
  store.clear();
@@ -16351,7 +16592,7 @@ var aclStore = {
16351
16592
  clear() {
16352
16593
  store.clear();
16353
16594
  try {
16354
- localStorage.removeItem(STORAGE_KEY2);
16595
+ localStorage.removeItem(STORAGE_KEY3);
16355
16596
  } catch {
16356
16597
  }
16357
16598
  }
@@ -17149,7 +17390,76 @@ function scriptJson(value) {
17149
17390
  }
17150
17391
  function renderNappletNamespacePrelude(options) {
17151
17392
  const domains = uniqueBareDomains(options.domains);
17152
- return `<script data-kehto-nip5d-injection>(${nappletNamespacePrelude.toString()})(${scriptJson(domains)}, (${createIntentUriNormalizer.toString()})());<\/script>`;
17393
+ const frameLock = options.experimental?.nestedContextLock ? nappletFrameLock.toString() : "(function(){})";
17394
+ return `<script data-kehto-nip5d-injection>(${nappletNamespacePrelude.toString()})(${scriptJson(domains)}, (${createIntentUriNormalizer.toString()})(), ${frameLock});<\/script>`;
17395
+ }
17396
+ function nappletFrameLock(win) {
17397
+ const FRAME_ELEMENTS2 = /* @__PURE__ */ new Set([
17398
+ "iframe",
17399
+ "frame",
17400
+ "frameset",
17401
+ "object",
17402
+ "embed",
17403
+ "portal",
17404
+ "fencedframe"
17405
+ ]);
17406
+ const isFrameTag = (value) => FRAME_ELEMENTS2.has(String(value).toLowerCase());
17407
+ const FRAME_TAG2 = /<\/?(?:iframe|frame|frameset|object|embed|portal|fencedframe)(?=[\s/>]|$)/i;
17408
+ const FRAME_TAG_PREFIX = /<[a-zA-Z]*$/;
17409
+ const { trustedTypes } = win;
17410
+ if (trustedTypes) {
17411
+ try {
17412
+ trustedTypes.createPolicy("default", {
17413
+ createHTML: (input, ...rest) => {
17414
+ const sink = rest.length >= 2 ? String(rest[1]) : "";
17415
+ const blocked = /write/i.test(sink) ? FRAME_TAG2.test(input) || FRAME_TAG_PREFIX.test(input) : FRAME_TAG2.test(input);
17416
+ if (blocked) throw new TypeError("kehto: napplets may not create nested browsing contexts");
17417
+ return input;
17418
+ },
17419
+ createScript: (input) => input,
17420
+ createScriptURL: (input) => input
17421
+ });
17422
+ } catch {
17423
+ }
17424
+ }
17425
+ const pin = (object, name, value) => {
17426
+ try {
17427
+ Object.defineProperty(object, name, {
17428
+ value,
17429
+ writable: false,
17430
+ configurable: false,
17431
+ enumerable: false
17432
+ });
17433
+ } catch {
17434
+ }
17435
+ };
17436
+ const localName = (qualified) => String(qualified ?? "").split(":").pop().toLowerCase();
17437
+ const HTML_NS = "http://www.w3.org/1999/xhtml";
17438
+ const docProto = win.Document?.prototype;
17439
+ if (docProto) {
17440
+ const createElement = docProto.createElement;
17441
+ pin(docProto, "createElement", function(tagName, ...rest) {
17442
+ if (isFrameTag(tagName)) throw new TypeError("kehto: napplets may not create nested browsing contexts");
17443
+ return createElement.call(this, tagName, ...rest);
17444
+ });
17445
+ const createElementNS = docProto.createElementNS;
17446
+ pin(docProto, "createElementNS", function(namespace, qualifiedName, ...rest) {
17447
+ if (namespace === HTML_NS && FRAME_ELEMENTS2.has(localName(qualifiedName))) {
17448
+ throw new TypeError("kehto: napplets may not create nested browsing contexts");
17449
+ }
17450
+ return createElementNS.call(this, namespace, qualifiedName, ...rest);
17451
+ });
17452
+ }
17453
+ const domImpl = win.DOMImplementation?.prototype;
17454
+ if (domImpl) {
17455
+ const createDocument = domImpl.createDocument;
17456
+ pin(domImpl, "createDocument", function(namespace, qualifiedName, ...rest) {
17457
+ if (namespace === HTML_NS && FRAME_ELEMENTS2.has(localName(qualifiedName))) {
17458
+ throw new TypeError("kehto: napplets may not create nested browsing contexts");
17459
+ }
17460
+ return createDocument.call(this, namespace, qualifiedName, ...rest);
17461
+ });
17462
+ }
17153
17463
  }
17154
17464
  function injectNappletNamespacePrelude(html, options) {
17155
17465
  const prelude = renderNappletNamespacePrelude(options);
@@ -17165,7 +17475,7 @@ function injectNappletNamespacePrelude(html, options) {
17165
17475
  }
17166
17476
  return `${prelude}${html}`;
17167
17477
  }
17168
- function nappletNamespacePrelude(domains, normalizeIntentUri2) {
17478
+ function nappletNamespacePrelude(domains, normalizeIntentUri2, frameLock) {
17169
17479
  const target = window;
17170
17480
  const allowed2 = new Set(domains);
17171
17481
  const requestTimeoutMs = 3e4;
@@ -17191,6 +17501,7 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2) {
17191
17501
  } catch {
17192
17502
  }
17193
17503
  }
17504
+ frameLock(target);
17194
17505
  function id() {
17195
17506
  if (target.crypto?.randomUUID) return target.crypto.randomUUID();
17196
17507
  return `napplet-${Date.now()}-${Math.random().toString(16).slice(2)}`;
@@ -18865,7 +19176,7 @@ function requireBootstrapScripts(directive, sources2) {
18865
19176
  throw new Error(`CSP ${directive} must allow the shell's inline namespace bootstrap`);
18866
19177
  }
18867
19178
  }
18868
- function buildNappletCsp(options = {}) {
19179
+ function buildNappletCsp(options = {}, lockTrustedTypes = false) {
18869
19180
  const grants = [...new Set((options.connectOrigins ?? []).map(connectionOrigin))].sort();
18870
19181
  const policy = {
18871
19182
  ...DEFAULT_DIRECTIVES,
@@ -18887,16 +19198,60 @@ function buildNappletCsp(options = {}) {
18887
19198
  }
18888
19199
  requireBootstrapScripts("script-src", policy["script-src"]);
18889
19200
  if (policy["script-src-elem"]) requireBootstrapScripts("script-src-elem", policy["script-src-elem"]);
18890
- return Object.entries(policy).map(([name, sources2]) => `${name} ${sources2.join(" ")}`).join("; ");
19201
+ const sourceLists = Object.entries(policy).map(([name, sources2]) => `${name} ${sources2.join(" ")}`);
19202
+ if (lockTrustedTypes) sourceLists.push(TRUSTED_TYPES_DIRECTIVES);
19203
+ return sourceLists.join("; ");
18891
19204
  }
18892
- function renderNappletCspMeta(options = {}) {
18893
- const policy = buildNappletCsp(options).replace(/&/g, "&amp;").replace(/"/g, "&quot;");
19205
+ var TRUSTED_TYPES_DIRECTIVES = "require-trusted-types-for 'script'; trusted-types default";
19206
+ function renderNappletCspMeta(options = {}, lockTrustedTypes = false) {
19207
+ const policy = buildNappletCsp(options, lockTrustedTypes).replace(/&/g, "&amp;").replace(/"/g, "&quot;");
18894
19208
  return `<meta http-equiv="Content-Security-Policy" content="${policy}">`;
18895
19209
  }
18896
19210
  function prepareNappletSrcdoc(html, options) {
18897
- const meta = renderNappletCspMeta(options.csp);
19211
+ const lockNestedContexts = options.experimental?.nestedContextLock === true;
19212
+ const meta = renderNappletCspMeta(options.csp, lockNestedContexts);
18898
19213
  return insertNappletHead(html, meta + renderNappletNamespacePrelude(options));
18899
19214
  }
19215
+ var FRAME_ELEMENTS = /* @__PURE__ */ new Set([
19216
+ "iframe",
19217
+ "frame",
19218
+ "frameset",
19219
+ "object",
19220
+ "embed",
19221
+ "portal",
19222
+ "fencedframe"
19223
+ ]);
19224
+ var FRAME_TAG = /<\/?(?:iframe|frame|frameset|object|embed|portal|fencedframe)(?=[\s/>]|$)/i;
19225
+ function subtreeHasFrame(root) {
19226
+ for (const element2 of Array.from(root.querySelectorAll("*"))) {
19227
+ const local = (element2.localName || "").toLowerCase();
19228
+ if (element2.namespaceURI === "http://www.w3.org/1999/xhtml" && FRAME_ELEMENTS.has(local)) {
19229
+ return true;
19230
+ }
19231
+ const template = element2;
19232
+ if (local === "template" && template.content && subtreeHasFrame(template.content)) return true;
19233
+ if (element2.shadowRoot && subtreeHasFrame(element2.shadowRoot)) return true;
19234
+ }
19235
+ return false;
19236
+ }
19237
+ function nappletMarkupHasFrame(html) {
19238
+ if (typeof html !== "string") return false;
19239
+ const DOMParser = globalThis.DOMParser;
19240
+ if (DOMParser) {
19241
+ try {
19242
+ return subtreeHasFrame(new DOMParser().parseFromString(html, "text/html"));
19243
+ } catch {
19244
+ }
19245
+ }
19246
+ return FRAME_TAG.test(html);
19247
+ }
19248
+ function assertNappletHasNoFrame(html) {
19249
+ if (nappletMarkupHasFrame(html)) {
19250
+ throw new Error(
19251
+ "kehto: napplet markup declares a nested browsing context (iframe/frame/object/embed); rejected before load"
19252
+ );
19253
+ }
19254
+ }
18900
19255
 
18901
19256
  // src/browser-console-panel.ts
18902
19257
  var PAJA_CONSOLE_PANEL_STORAGE_KEY = "kehto:paja:console:v1";
@@ -25159,8 +25514,14 @@ async function navigateFrame(frame, config, generation2, adapter, resolvedTarget
25159
25514
  console.warn(`[paja] Napplet requires unsupported NAP capabilities: ${missing.join(", ")}; full functionality may be unavailable.`);
25160
25515
  }
25161
25516
  }
25517
+ const lockSetting = readStoredNestedContextLockSetting() ?? config.experimental?.nestedContextLock ?? "auto";
25518
+ const nestedContextLock = resolveNestedContextLock(lockSetting, domains);
25519
+ if (nestedContextLock) {
25520
+ assertNappletHasNoFrame(resolvedTarget.indexHtml);
25521
+ }
25162
25522
  const srcdoc = prepareNappletSrcdoc(resolvedTarget.indexHtml, {
25163
25523
  domains,
25524
+ ...nestedContextLock ? { experimental: { nestedContextLock: true } } : {},
25164
25525
  csp: {
25165
25526
  ...config.csp,
25166
25527
  connectOrigins: [
@@ -25186,6 +25547,12 @@ async function navigateFrame(frame, config, generation2, adapter, resolvedTarget
25186
25547
  );
25187
25548
  return registeredWindowId;
25188
25549
  }
25550
+ var PRIVACY_SENSITIVE_DOMAINS = /* @__PURE__ */ new Set(["dm"]);
25551
+ function resolveNestedContextLock(setting, grantedDomains) {
25552
+ if (setting === "on") return true;
25553
+ if (setting === "off") return false;
25554
+ return grantedDomains.some((domain) => PRIVACY_SENSITIVE_DOMAINS.has(domain));
25555
+ }
25189
25556
  function renderTargetErrorHtml(error) {
25190
25557
  const message3 = error instanceof Error ? error.message : String(error);
25191
25558
  return `<!doctype html><html><body><pre>${escapeHtml(message3)}</pre></body></html>`;
@@ -29596,6 +29963,8 @@ async function installPajaHost() {
29596
29963
  const disposeSidebarSections = installPajaSidebarSections();
29597
29964
  window.addEventListener("pagehide", disposeSidebarSections, { once: true });
29598
29965
  const resourceSettings = installPajaResourceSettings();
29966
+ const securitySettings = installPajaSecuritySettings();
29967
+ window.addEventListener("pagehide", securitySettings.dispose, { once: true });
29599
29968
  const config = await readLatestPajaHostConfig(readPajaHostConfig());
29600
29969
  const stage = getStage();
29601
29970
  const frame = config.target.mode === "runtime-pointer" ? null : getFrame();