@kehto/paja 0.21.1 → 0.21.3

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.
package/README.md CHANGED
@@ -397,6 +397,11 @@ boundary and is advertised because each request may provide server locations
397
397
  without a host default. For example, reads accept
398
398
  `blossom:<hash>.gbc?xs=cdn.example&as=<pubkey>&sz=32768` and
399
399
  `blossom:sha256:<hash>.gbc?xs=cdn.example&sz=32768`.
400
+ Internal event-reference keys and synthesized references use `blossom:<hash>`.
401
+ Napplet-supplied resource cache keys remain unchanged, as NAP-RESOURCE does not
402
+ require URL canonicalization. Actual `sha256:` alias reads/server-resolution
403
+ requests emit `KEHTO_COMPAT_BLOSSOM_SHA256` once per host module lifetime, with
404
+ replacement guidance and no URL/hash payload. Canonical requests stay quiet.
400
405
  Repeated `xs` and `as` are supported without an observed event. Paja accepts only
401
406
  public-looking HTTPS origin hints (scheme-less domains use HTTPS), discards
402
407
  invalid/private literals, and deduplicates them. Unlike BUD-10's suggested HTTP
@@ -4242,6 +4242,44 @@ function relayEventResultFromCarrier(carrier) {
4242
4242
  }
4243
4243
  return null;
4244
4244
  }
4245
+ function createServiceExtensionRouter(context) {
4246
+ const { hooks, services, registrations, sessions, acl, enforce, firewall } = context;
4247
+ const windowLifetimes = /* @__PURE__ */ new Map();
4248
+ function handleMessage(windowId, message2) {
4249
+ const dot = message2.type.indexOf(".");
4250
+ const domain = message2.type.slice(0, dot);
4251
+ if (dot <= 0 || dot === message2.type.length - 1 || !/^[a-z][a-z0-9-]*$/.test(domain) || !Object.hasOwn(services, domain)) return;
4252
+ const handler = services[domain];
4253
+ const policies = handler.messageCapabilities;
4254
+ if (!policies || !Object.hasOwn(policies, message2.type)) return;
4255
+ const capability = policies[message2.type];
4256
+ if (capability !== null && !ALL_CAPABILITIES.includes(capability)) return;
4257
+ const session = sessions.getEntryByWindowId(windowId);
4258
+ const registration = registrations.get(domain);
4259
+ if (!session || !registration) return;
4260
+ const allowed2 = () => hooks.isDomainAllowed?.(windowId, domain) === true && !acl.isBlocked("", session.dTag, session.aggregateHash) && (capability === null || enforce(windowId, capability, message2).allowed);
4261
+ if (!allowed2() || firewall(windowId, message2, capability, false) === "drop") return;
4262
+ let lifetime = windowLifetimes.get(windowId);
4263
+ if (!lifetime) {
4264
+ lifetime = {};
4265
+ windowLifetimes.set(windowId, lifetime);
4266
+ }
4267
+ handler.handleMessage(windowId, message2, (response) => {
4268
+ if (registrations.get(domain) !== registration || services[domain] !== handler || windowLifetimes.get(windowId) !== lifetime || sessions.getEntryByWindowId(windowId) !== session) return;
4269
+ if (!response || typeof response.type !== "string" || !response.type.startsWith(`${domain}.`) || response.type.length <= dot + 1) return;
4270
+ if (allowed2()) hooks.sendToNapplet(windowId, response);
4271
+ });
4272
+ }
4273
+ return {
4274
+ handleMessage,
4275
+ destroyWindow(windowId) {
4276
+ windowLifetimes.delete(windowId);
4277
+ },
4278
+ destroy() {
4279
+ windowLifetimes.clear();
4280
+ }
4281
+ };
4282
+ }
4245
4283
  function notifyServiceWindowDestroyed(windowId, services) {
4246
4284
  for (const handler of Object.values(services)) {
4247
4285
  try {
@@ -5494,13 +5532,18 @@ function buildObservation(envelope, windowId, senderCap, sessionRegistry2, getFo
5494
5532
  }
5495
5533
  function createFirewallGate(config) {
5496
5534
  const { firewallState, sessionRegistry: sessionRegistry2, hooks, fireConsent } = config;
5497
- return function firewallGate(windowId, envelope, senderCap) {
5535
+ return function firewallGate(windowId, envelope, senderCap, respond = true) {
5498
5536
  const obs = buildObservation(envelope, windowId, senderCap, sessionRegistry2, hooks.getFocusContext);
5499
5537
  const result2 = firewallState.evaluate(obs);
5500
5538
  const { decision, action, ruleId, reason } = result2;
5501
5539
  const napplet = obs.napplet;
5502
5540
  const opClass = obs.opClass;
5503
5541
  if (decision === "reject" || decision === "prompt") {
5542
+ if (!respond) {
5543
+ hooks.onFirewallEvent?.({ windowId, napplet, opClass, decision, action, ruleId, reason, message: envelope });
5544
+ if (decision === "prompt") fireConsent(windowId, napplet);
5545
+ return "drop";
5546
+ }
5504
5547
  const intentDenial = createIntentPolicyDenial(envelope);
5505
5548
  if (intentDenial) {
5506
5549
  hooks.sendToNapplet(windowId, intentDenial);
@@ -5551,7 +5594,7 @@ function createDenialResponse(envelope, error) {
5551
5594
  const type = denialResponseType(envelope);
5552
5595
  return type ? { type, id, error } : null;
5553
5596
  }
5554
- function createMessageHandler(hooks, sessionRegistry2, enforceNap, dispatchNapEnvelope, firewallGate) {
5597
+ function createMessageHandler(hooks, sessionRegistry2, enforceNap, dispatchNapEnvelope, serviceRouting, firewallGate) {
5555
5598
  return (windowId, msg) => {
5556
5599
  if (typeof msg !== "object" || msg === null || Array.isArray(msg) || !("type" in msg) || typeof msg.type !== "string") return;
5557
5600
  const envelope = msg;
@@ -5559,6 +5602,10 @@ function createMessageHandler(hooks, sessionRegistry2, enforceNap, dispatchNapEn
5559
5602
  if (dotIdx === -1) return;
5560
5603
  if (!sessionRegistry2.getEntryByWindowId(windowId)) return;
5561
5604
  const domain = envelope.type.slice(0, dotIdx);
5605
+ if (!serviceRouting.builtInDomains.has(domain)) {
5606
+ serviceRouting.extensions.handleMessage(windowId, envelope);
5607
+ return;
5608
+ }
5562
5609
  if (hooks.isDomainAllowed && !hooks.isDomainAllowed(windowId, domain)) return;
5563
5610
  if (isIdentityOrThemeMessage(envelope) && !createCanonicalDomainResult(envelope)) return;
5564
5611
  const caps = resolveCapabilitiesNap(envelope);
@@ -5611,7 +5658,8 @@ function createRuntimeInstance(context) {
5611
5658
  serviceRegistry,
5612
5659
  sessionRegistry: sessionRegistry2,
5613
5660
  subscriptions,
5614
- consentHandlerRef
5661
+ consentHandlerRef,
5662
+ extensions
5615
5663
  } = context;
5616
5664
  const undeclaredServiceConsents = /* @__PURE__ */ new Set();
5617
5665
  const attachedServices = /* @__PURE__ */ new Map();
@@ -5675,6 +5723,8 @@ function createRuntimeInstance(context) {
5675
5723
  eventBuffer.bufferAndDeliver(createInjectedEvent(hooks, topic, payload), null);
5676
5724
  },
5677
5725
  destroy() {
5726
+ extensions.destroy();
5727
+ registeredServices.clear();
5678
5728
  for (const name of attachedServices.keys()) detachService(name);
5679
5729
  manifestCache2.persist();
5680
5730
  aclState.persist();
@@ -5683,13 +5733,13 @@ function createRuntimeInstance(context) {
5683
5733
  subscriptions.clear();
5684
5734
  incRuntime.clear();
5685
5735
  eventBuffer.clear();
5686
- registeredServices.clear();
5687
5736
  undeclaredServiceConsents.clear();
5688
5737
  },
5689
5738
  registerConsentHandler(handler) {
5690
5739
  consentHandlerRef.current = handler;
5691
5740
  },
5692
5741
  registerService(name, handler) {
5742
+ registeredServices.delete(name);
5693
5743
  detachService(name);
5694
5744
  serviceRegistry[name] = handler;
5695
5745
  registeredServices.set(name, {
@@ -5700,11 +5750,12 @@ function createRuntimeInstance(context) {
5700
5750
  attachService(name, handler);
5701
5751
  },
5702
5752
  unregisterService(name) {
5753
+ registeredServices.delete(name);
5703
5754
  detachService(name);
5704
5755
  delete serviceRegistry[name];
5705
- registeredServices.delete(name);
5706
5756
  },
5707
5757
  destroyWindow(windowId) {
5758
+ extensions.destroyWindow(windowId);
5708
5759
  for (const [key] of subscriptions) {
5709
5760
  if (key.startsWith(`${windowId}:`)) {
5710
5761
  subscriptions.delete(key);
@@ -5733,8 +5784,10 @@ function createRuntime(hooks) {
5733
5784
  const serviceRegistry = { ...hooks.services };
5734
5785
  const registeredServices = createRegisteredServices(serviceRegistry);
5735
5786
  const firewallState = createFirewallState(hooks.firewallPersistence);
5787
+ let extensions;
5736
5788
  const sessionRegistry2 = createSessionRegistry(hooks.onPendingUpdate, (windowId) => {
5737
5789
  firewallState.resetInitBudget(windowId);
5790
+ extensions?.destroyWindow(windowId);
5738
5791
  });
5739
5792
  let incRuntime = null;
5740
5793
  const aclState = createAclState(hooks.aclPersistence, "permissive", (mutation) => {
@@ -5797,14 +5850,25 @@ function createRuntime(hooks) {
5797
5850
  firewallState.load();
5798
5851
  manifestCache2.load();
5799
5852
  const domainHandlers = createRuntimeDomainHandlers({ hooks, serviceRegistry, sessionRegistry: sessionRegistry2, aclState });
5800
- const dispatchNapEnvelope = createNapEnvelopeDispatcher({
5853
+ const napHandlers = {
5801
5854
  relay: createRelayHandler({ hooks, serviceRegistry, subscriptions, eventBuffer, replayDetector }),
5802
5855
  identity: createIdentityHandler({ hooks, serviceRegistry }),
5803
5856
  count: createCountHandler({ hooks, serviceRegistry }),
5804
5857
  inc: incRuntime.handleMessage,
5805
5858
  ...domainHandlers
5859
+ };
5860
+ const dispatchNapEnvelope = createNapEnvelopeDispatcher(napHandlers);
5861
+ const builtInDomains = /* @__PURE__ */ new Set([...Object.keys(napHandlers), "shell", "signer"]);
5862
+ extensions = createServiceExtensionRouter({
5863
+ hooks,
5864
+ services: serviceRegistry,
5865
+ registrations: registeredServices,
5866
+ sessions: sessionRegistry2,
5867
+ acl: aclState,
5868
+ enforce: enforceNap,
5869
+ firewall: firewallGate
5806
5870
  });
5807
- const handleMessage = createMessageHandler(hooks, sessionRegistry2, enforceNap, dispatchNapEnvelope, firewallGate);
5871
+ const handleMessage = createMessageHandler(hooks, sessionRegistry2, enforceNap, dispatchNapEnvelope, { builtInDomains, extensions }, firewallGate);
5808
5872
  return createRuntimeInstance({
5809
5873
  hooks,
5810
5874
  serviceRegistry,
@@ -5818,7 +5882,8 @@ function createRuntime(hooks) {
5818
5882
  firewallState,
5819
5883
  manifestCache: manifestCache2,
5820
5884
  consentHandlerRef,
5821
- handleMessage
5885
+ handleMessage,
5886
+ extensions
5822
5887
  });
5823
5888
  }
5824
5889
 
@@ -12598,12 +12663,20 @@ function parsePajaBlossomUri(value) {
12598
12663
  const servers = [];
12599
12664
  for (const server of params.getAll("xs")) appendHint(servers, server);
12600
12665
  const hash = match[1].toLowerCase();
12601
- return { hash, canonical: `blossom:sha256:${hash}`, extension: match[2], servers, authors, expectedSize };
12666
+ return { hash, canonical: `blossom:${hash}`, extension: match[2], servers, authors, expectedSize };
12602
12667
  }
12603
12668
  function appendHint(target, value) {
12604
12669
  if (target.length < MAX_HINTS && !target.includes(value)) target.push(value);
12605
12670
  }
12606
12671
 
12672
+ // src/browser-blossom-compat.ts
12673
+ var warned = false;
12674
+ function warnLegacyBlossomPrefix(value) {
12675
+ if (warned || !/^blossom:sha256:/i.test(value)) return;
12676
+ warned = true;
12677
+ console.warn("[KEHTO_COMPAT_BLOSSOM_SHA256] Replace blossom:sha256:<hash> with blossom:<hash>; preserve any extension and hints. Warning shown once per host module lifetime.");
12678
+ }
12679
+
12607
12680
  // src/browser-resource.ts
12608
12681
  var PAJA_RESOURCE_MAX_BYTES = 10 * 1024 * 1024;
12609
12682
  var PAJA_RESOURCE_MAX_URLS = 100;
@@ -12744,6 +12817,7 @@ async function fetchBlossomResource(value, signal, requestServers, windowId, opt
12744
12817
  if (!parsed) {
12745
12818
  throw new ResourceServiceError("invalid-request", "invalid Blossom URI");
12746
12819
  }
12820
+ warnLegacyBlossomPrefix(value);
12747
12821
  if (parsed.expectedSize !== void 0 && parsed.expectedSize > PAJA_RESOURCE_MAX_BYTES) throw resourceTooLarge();
12748
12822
  const expectedHash = parsed.hash;
12749
12823
  const configuredServers = await options.getBlossomServers?.({ url: value, windowId }) ?? [];
@@ -15505,7 +15579,7 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2) {
15505
15579
  const legacy = /* @__PURE__ */ new Map();
15506
15580
  const pending = [];
15507
15581
  let draining = false;
15508
- let warned = false;
15582
+ let warned2 = false;
15509
15583
  function drain() {
15510
15584
  if (draining) return;
15511
15585
  draining = true;
@@ -15516,8 +15590,8 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2) {
15516
15590
  const [delivery] = pending.splice(index, 1);
15517
15591
  const canonical = handlers.size > 0;
15518
15592
  const recipients = canonical ? [...handlers] : [...legacy.entries()].filter(([, topic]) => topic === delivery.convention).map(([handler]) => handler);
15519
- if (!canonical && !warned) {
15520
- warned = true;
15593
+ if (!canonical && !warned2) {
15594
+ warned2 = true;
15521
15595
  console.warn("[KEHTO_COMPAT_INTENT_INC] Intent delivered to a legacy INC listener. Migrate to window.napplet.intent.onDelivery. See docs/compatibility.md.");
15522
15596
  }
15523
15597
  for (const handler of recipients) {
@@ -18637,6 +18711,7 @@ function createPajaBlossomEventResolver(options) {
18637
18711
  async function getServers(url, windowId) {
18638
18712
  const parsed = parseBlossomReference(url);
18639
18713
  if (!parsed) return [];
18714
+ warnLegacyBlossomPrefix(url);
18640
18715
  const canonical = parsed.url;
18641
18716
  const contexts = canonical && windowId ? windows.get(windowId)?.get(canonical) ?? [] : [];
18642
18717
  const servers = [...parsed.servers];
@@ -18758,7 +18833,7 @@ function extractEventResourceLocations(event) {
18758
18833
  if ((tag[0] === "resource" || tag[0] === "r") && typeof tag[1] === "string") {
18759
18834
  add(tag[1]);
18760
18835
  } else if (tag[0] === "blossom" && typeof tag[1] === "string") {
18761
- add(HEX_642.test(tag[1]) ? `blossom:sha256:${tag[1]}` : tag[1]);
18836
+ add(HEX_642.test(tag[1]) ? `blossom:${tag[1]}` : tag[1]);
18762
18837
  }
18763
18838
  }
18764
18839
  const content = parseEventContent(event.content);
@@ -18773,7 +18848,7 @@ function extractEventResourceLocations(event) {
18773
18848
  continue;
18774
18849
  }
18775
18850
  if (!isRecord5(entry)) continue;
18776
- const value = stringValue(entry.uri) ?? stringValue(entry.url) ?? stringValue(entry.resource) ?? (isBlossomRecord(entry) && isHash(entry.sha256) ? `blossom:sha256:${String(entry.sha256)}` : void 0);
18851
+ const value = stringValue(entry.uri) ?? stringValue(entry.url) ?? stringValue(entry.resource) ?? (isBlossomRecord(entry) && isHash(entry.sha256) ? `blossom:${String(entry.sha256)}` : void 0);
18777
18852
  add(value, [...contentServers, ...stringList2(entry.servers)], stringList2(entry.authors));
18778
18853
  }
18779
18854
  }