@kehto/paja 0.21.2 → 0.21.4

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
@@ -3187,6 +3187,17 @@ function unblock(state, identity) {
3187
3187
  }
3188
3188
  };
3189
3189
  }
3190
+ function setQuota(state, identity, bytes) {
3191
+ const key = toKey(identity);
3192
+ const entry = getEntry(state, key);
3193
+ return {
3194
+ ...state,
3195
+ entries: {
3196
+ ...state.entries,
3197
+ [key]: { ...entry, quota: bytes }
3198
+ }
3199
+ };
3200
+ }
3190
3201
  function getQuota(state, identity) {
3191
3202
  const key = toKey(identity);
3192
3203
  const entry = state.entries[key];
@@ -3775,10 +3786,10 @@ function createSessionRegistry(notifier, onRegister) {
3775
3786
  },
3776
3787
  unregister(windowId) {
3777
3788
  const pubkey2 = byWindowId2.get(windowId);
3778
- if (pubkey2) {
3789
+ if (pubkey2 !== void 0 && byPubkey2.get(pubkey2)?.windowId === windowId) {
3779
3790
  byPubkey2.delete(pubkey2);
3780
- byWindowId2.delete(windowId);
3781
3791
  }
3792
+ byWindowId2.delete(windowId);
3782
3793
  byWindowIdEntry.delete(windowId);
3783
3794
  pendingUpdates2.delete(windowId);
3784
3795
  },
@@ -3939,15 +3950,20 @@ function createAclState(persistence, defaultPolicy = "permissive", onMutation) {
3939
3950
  if (!entry) return void 0;
3940
3951
  return {
3941
3952
  pubkey: pubkey2 || "",
3953
+ dTag,
3954
+ aggregateHash,
3942
3955
  capabilities: bitsToCapabilities(entry.caps),
3943
3956
  blocked: entry.blocked,
3944
3957
  stateQuota: entry.quota
3945
3958
  };
3946
3959
  },
3947
3960
  getAllEntries() {
3948
- return Object.entries(state.entries).map(([, entry]) => {
3961
+ return Object.entries(state.entries).map(([key, entry]) => {
3962
+ const separator = key.lastIndexOf(":");
3949
3963
  return {
3950
3964
  pubkey: "",
3965
+ dTag: key.slice(0, separator),
3966
+ aggregateHash: key.slice(separator + 1),
3951
3967
  capabilities: bitsToCapabilities(entry.caps),
3952
3968
  blocked: entry.blocked,
3953
3969
  stateQuota: entry.quota
@@ -3958,10 +3974,20 @@ function createAclState(persistence, defaultPolicy = "permissive", onMutation) {
3958
3974
  const id = toIdentity(pubkey2, dTag, aggregateHash);
3959
3975
  return getQuota(state, id);
3960
3976
  },
3977
+ setStateQuota(pubkey2, dTag, aggregateHash, bytes) {
3978
+ if (!Number.isSafeInteger(bytes) || bytes < 0) {
3979
+ throw new RangeError("State quota must be a non-negative safe integer byte count");
3980
+ }
3981
+ const id = toIdentity(pubkey2, dTag, aggregateHash);
3982
+ ensureRuntimeDefaultEntry(id);
3983
+ state = setQuota(state, id, bytes);
3984
+ },
3961
3985
  persist() {
3962
3986
  try {
3963
3987
  persistence.persist(serialize(state));
3988
+ return true;
3964
3989
  } catch {
3990
+ return false;
3965
3991
  }
3966
3992
  },
3967
3993
  load() {
@@ -3977,7 +4003,9 @@ function createAclState(persistence, defaultPolicy = "permissive", onMutation) {
3977
4003
  state = createState(defaultPolicy);
3978
4004
  try {
3979
4005
  persistence.persist("");
4006
+ return true;
3980
4007
  } catch {
4008
+ return false;
3981
4009
  }
3982
4010
  }
3983
4011
  };
@@ -4335,12 +4363,17 @@ function handleRelaySubscribe(context, windowId, msg, m) {
4335
4363
  const filters = m.filters ?? [];
4336
4364
  if (!subId) return;
4337
4365
  const subKey = `${windowId}:${subId}`;
4338
- subscriptions.set(subKey, { windowId, filters });
4366
+ const entry = { windowId, filters };
4367
+ subscriptions.set(subKey, entry);
4368
+ const isActive = () => subscriptions.get(subKey) === entry && context.canReadRelay(windowId);
4369
+ const send = (response) => {
4370
+ if (isActive()) hooks.sendToNapplet(windowId, normalizeRelayServiceResponse(response));
4371
+ };
4339
4372
  const seenIds = /* @__PURE__ */ new Set();
4340
4373
  function deliver(event, relayHints) {
4341
4374
  if (seenIds.has(event.id)) return;
4342
4375
  seenIds.add(event.id);
4343
- if (subscriptions.has(subKey)) {
4376
+ if (isActive()) {
4344
4377
  sendRelayEvent(hooks, windowId, subId, createRelayEventResultWithHints(event, relayHints));
4345
4378
  }
4346
4379
  }
@@ -4351,22 +4384,16 @@ function handleRelaySubscribe(context, windowId, msg, m) {
4351
4384
  const relayService = relayServiceFrom(context);
4352
4385
  const cacheService = !serviceRegistry["relay"] ? serviceRegistry["cache"] : void 0;
4353
4386
  if (!isShellKind && relayService) {
4354
- relayService.handleMessage(windowId, msg, (resp) => {
4355
- if (!subscriptions.has(subKey)) return;
4356
- hooks.sendToNapplet(windowId, normalizeRelayServiceResponse(resp));
4357
- });
4358
- if (cacheService) {
4359
- cacheService.handleMessage(windowId, msg, (resp) => {
4360
- if (!subscriptions.has(subKey)) return;
4361
- hooks.sendToNapplet(windowId, normalizeRelayServiceResponse(resp));
4362
- });
4363
- }
4387
+ relayService.handleMessage(windowId, msg, send);
4388
+ if (cacheService && isActive()) cacheService.handleMessage(windowId, msg, send);
4389
+ if (!isActive()) closeRelayBackends(context, windowId, subId, subKey);
4364
4390
  return;
4365
4391
  }
4366
4392
  const relayHint = typeof m.relay === "string" && m.relay.length > 0 ? m.relay : void 0;
4367
- deliverFromRuntimeBackends(context, windowId, subId, subKey, filters, isShellKind, deliver, relayHint);
4393
+ if (!isActive()) return;
4394
+ deliverFromRuntimeBackends(context, subId, subKey, filters, isShellKind, deliver, send, isActive, relayHint);
4368
4395
  }
4369
- function deliverFromRuntimeBackends(context, windowId, subId, subKey, filters, isShellKind, deliver, relayHint) {
4396
+ function deliverFromRuntimeBackends(context, subId, subKey, filters, isShellKind, deliver, send, isActive, relayHint) {
4370
4397
  const { hooks } = context;
4371
4398
  const cache2 = hooks.cache;
4372
4399
  if (cache2?.isAvailable() && !isShellKind) {
@@ -4377,7 +4404,7 @@ function deliverFromRuntimeBackends(context, windowId, subId, subKey, filters, i
4377
4404
  }
4378
4405
  const pool = hooks.relayPool;
4379
4406
  if (!pool?.isAvailable() && !isShellKind) {
4380
- hooks.sendToNapplet(windowId, { type: "relay.eose", subId });
4407
+ send({ type: "relay.eose", subId });
4381
4408
  return;
4382
4409
  }
4383
4410
  if (!pool?.isAvailable() || isShellKind) return;
@@ -4386,15 +4413,16 @@ function deliverFromRuntimeBackends(context, windowId, subId, subKey, filters, i
4386
4413
  const eoseFallbackTimer = setTimeout(() => {
4387
4414
  if (!eoseSent) {
4388
4415
  eoseSent = true;
4389
- hooks.sendToNapplet(windowId, { type: "relay.eose", subId });
4416
+ send({ type: "relay.eose", subId });
4390
4417
  }
4391
4418
  }, 15e3);
4392
4419
  const subscription = pool.subscribe(filters, (item) => {
4420
+ if (!isActive()) return;
4393
4421
  if (item === "EOSE") {
4394
4422
  clearTimeout(eoseFallbackTimer);
4395
4423
  if (!eoseSent) {
4396
4424
  eoseSent = true;
4397
- hooks.sendToNapplet(windowId, { type: "relay.eose", subId });
4425
+ send({ type: "relay.eose", subId });
4398
4426
  }
4399
4427
  return;
4400
4428
  }
@@ -4412,6 +4440,31 @@ function deliverFromRuntimeBackends(context, windowId, subId, subKey, filters, i
4412
4440
  clearTimeout(eoseFallbackTimer);
4413
4441
  subscription.unsubscribe();
4414
4442
  });
4443
+ if (!isActive()) pool.untrackSubscription(subKey);
4444
+ }
4445
+ function closeRelayBackends(context, windowId, subId, subKey) {
4446
+ const relay = context.serviceRegistry["relay"] ?? context.serviceRegistry["relay-pool"];
4447
+ const cache2 = !context.serviceRegistry["relay"] ? context.serviceRegistry["cache"] : void 0;
4448
+ for (const service of /* @__PURE__ */ new Set([relay, cache2])) {
4449
+ try {
4450
+ service?.handleMessage(windowId, { type: "relay.close", subId }, () => {
4451
+ });
4452
+ } catch {
4453
+ }
4454
+ }
4455
+ try {
4456
+ context.hooks.relayPool?.untrackSubscription(subKey);
4457
+ } catch {
4458
+ }
4459
+ }
4460
+ function revokeRelaySubscriptions(context, windowId) {
4461
+ const entries = [...context.subscriptions].filter(([, entry]) => entry.windowId === windowId);
4462
+ for (const [key] of entries) context.subscriptions.delete(key);
4463
+ for (const [key] of entries) {
4464
+ const subId = key.slice(windowId.length + 1);
4465
+ closeRelayBackends(context, windowId, subId, key);
4466
+ context.hooks.sendToNapplet(windowId, { type: "relay.closed", subId, reason: "denied: relay:read" });
4467
+ }
4415
4468
  }
4416
4469
  function handleRelayClose(context, windowId, msg, m) {
4417
4470
  const { hooks, subscriptions } = context;
@@ -5794,6 +5847,7 @@ function createRuntime(hooks) {
5794
5847
  if (mutation.type === "revoke" && mutation.capability !== "relay:read") return;
5795
5848
  for (const entry of sessionRegistry2.getAllEntries()) {
5796
5849
  if (entry.dTag === mutation.dTag && entry.aggregateHash === mutation.aggregateHash) {
5850
+ revokeRelaySubscriptions({ hooks, serviceRegistry, subscriptions }, entry.windowId);
5797
5851
  incRuntime?.revokeWindow(entry.windowId);
5798
5852
  }
5799
5853
  }
@@ -5851,7 +5905,17 @@ function createRuntime(hooks) {
5851
5905
  manifestCache2.load();
5852
5906
  const domainHandlers = createRuntimeDomainHandlers({ hooks, serviceRegistry, sessionRegistry: sessionRegistry2, aclState });
5853
5907
  const napHandlers = {
5854
- relay: createRelayHandler({ hooks, serviceRegistry, subscriptions, eventBuffer, replayDetector }),
5908
+ relay: createRelayHandler({
5909
+ hooks,
5910
+ serviceRegistry,
5911
+ subscriptions,
5912
+ eventBuffer,
5913
+ replayDetector,
5914
+ canReadRelay(windowId) {
5915
+ const entry = sessionRegistry2.getEntryByWindowId(windowId);
5916
+ return !!entry && aclState.check("", entry.dTag, entry.aggregateHash, "relay:read");
5917
+ }
5918
+ }),
5855
5919
  identity: createIdentityHandler({ hooks, serviceRegistry }),
5856
5920
  count: createCountHandler({ hooks, serviceRegistry }),
5857
5921
  inc: incRuntime.handleMessage,
@@ -12663,12 +12727,20 @@ function parsePajaBlossomUri(value) {
12663
12727
  const servers = [];
12664
12728
  for (const server of params.getAll("xs")) appendHint(servers, server);
12665
12729
  const hash = match[1].toLowerCase();
12666
- return { hash, canonical: `blossom:sha256:${hash}`, extension: match[2], servers, authors, expectedSize };
12730
+ return { hash, canonical: `blossom:${hash}`, extension: match[2], servers, authors, expectedSize };
12667
12731
  }
12668
12732
  function appendHint(target, value) {
12669
12733
  if (target.length < MAX_HINTS && !target.includes(value)) target.push(value);
12670
12734
  }
12671
12735
 
12736
+ // src/browser-blossom-compat.ts
12737
+ var warned = false;
12738
+ function warnLegacyBlossomPrefix(value) {
12739
+ if (warned || !/^blossom:sha256:/i.test(value)) return;
12740
+ warned = true;
12741
+ 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.");
12742
+ }
12743
+
12672
12744
  // src/browser-resource.ts
12673
12745
  var PAJA_RESOURCE_MAX_BYTES = 10 * 1024 * 1024;
12674
12746
  var PAJA_RESOURCE_MAX_URLS = 100;
@@ -12809,6 +12881,7 @@ async function fetchBlossomResource(value, signal, requestServers, windowId, opt
12809
12881
  if (!parsed) {
12810
12882
  throw new ResourceServiceError("invalid-request", "invalid Blossom URI");
12811
12883
  }
12884
+ warnLegacyBlossomPrefix(value);
12812
12885
  if (parsed.expectedSize !== void 0 && parsed.expectedSize > PAJA_RESOURCE_MAX_BYTES) throw resourceTooLarge();
12813
12886
  const expectedHash = parsed.hash;
12814
12887
  const configuredServers = await options.getBlossomServers?.({ url: value, windowId }) ?? [];
@@ -14234,10 +14307,10 @@ function registerNip5dSessionIfNeeded({
14234
14307
  if (existing && previousRegistration === sourceRegistrationId) {
14235
14308
  return;
14236
14309
  }
14310
+ state.environments.delete(windowId);
14237
14311
  if (existing && previousRegistration !== void 0) {
14238
14312
  runtime.destroyWindow(windowId);
14239
14313
  runtime.sessionRegistry.unregister(windowId);
14240
- state.environments.delete(windowId);
14241
14314
  }
14242
14315
  if (existing && previousRegistration === void 0) {
14243
14316
  state.sessionRegistration.set(windowId, sourceRegistrationId);
@@ -15570,7 +15643,7 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2) {
15570
15643
  const legacy = /* @__PURE__ */ new Map();
15571
15644
  const pending = [];
15572
15645
  let draining = false;
15573
- let warned = false;
15646
+ let warned2 = false;
15574
15647
  function drain() {
15575
15648
  if (draining) return;
15576
15649
  draining = true;
@@ -15581,8 +15654,8 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2) {
15581
15654
  const [delivery] = pending.splice(index, 1);
15582
15655
  const canonical = handlers.size > 0;
15583
15656
  const recipients = canonical ? [...handlers] : [...legacy.entries()].filter(([, topic]) => topic === delivery.convention).map(([handler]) => handler);
15584
- if (!canonical && !warned) {
15585
- warned = true;
15657
+ if (!canonical && !warned2) {
15658
+ warned2 = true;
15586
15659
  console.warn("[KEHTO_COMPAT_INTENT_INC] Intent delivered to a legacy INC listener. Migrate to window.napplet.intent.onDelivery. See docs/compatibility.md.");
15587
15660
  }
15588
15661
  for (const handler of recipients) {
@@ -18702,6 +18775,7 @@ function createPajaBlossomEventResolver(options) {
18702
18775
  async function getServers(url, windowId) {
18703
18776
  const parsed = parseBlossomReference(url);
18704
18777
  if (!parsed) return [];
18778
+ warnLegacyBlossomPrefix(url);
18705
18779
  const canonical = parsed.url;
18706
18780
  const contexts = canonical && windowId ? windows.get(windowId)?.get(canonical) ?? [] : [];
18707
18781
  const servers = [...parsed.servers];
@@ -18823,7 +18897,7 @@ function extractEventResourceLocations(event) {
18823
18897
  if ((tag[0] === "resource" || tag[0] === "r") && typeof tag[1] === "string") {
18824
18898
  add(tag[1]);
18825
18899
  } else if (tag[0] === "blossom" && typeof tag[1] === "string") {
18826
- add(HEX_642.test(tag[1]) ? `blossom:sha256:${tag[1]}` : tag[1]);
18900
+ add(HEX_642.test(tag[1]) ? `blossom:${tag[1]}` : tag[1]);
18827
18901
  }
18828
18902
  }
18829
18903
  const content = parseEventContent(event.content);
@@ -18838,7 +18912,7 @@ function extractEventResourceLocations(event) {
18838
18912
  continue;
18839
18913
  }
18840
18914
  if (!isRecord5(entry)) continue;
18841
- const value = stringValue(entry.uri) ?? stringValue(entry.url) ?? stringValue(entry.resource) ?? (isBlossomRecord(entry) && isHash(entry.sha256) ? `blossom:sha256:${String(entry.sha256)}` : void 0);
18915
+ const value = stringValue(entry.uri) ?? stringValue(entry.url) ?? stringValue(entry.resource) ?? (isBlossomRecord(entry) && isHash(entry.sha256) ? `blossom:${String(entry.sha256)}` : void 0);
18842
18916
  add(value, [...contentServers, ...stringList2(entry.servers)], stringList2(entry.authors));
18843
18917
  }
18844
18918
  }