@kernlize/core 0.8.0 → 0.10.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.
package/dist/index.js CHANGED
@@ -346,6 +346,10 @@ import { unixNow } from "applesauce-core/helpers";
346
346
  // src/applesauce/relay-hooks.ts
347
347
  import { normalizeRelayUrl as normalizeRelayUrl2 } from "applesauce-core/helpers";
348
348
  import { NAPPLET_KINDS } from "@kehto/nip/5d";
349
+ var SHELL_RELAY_OPTIONS = Object.freeze({
350
+ publishRetry: Object.freeze({ count: 1, delay: 1e3 }),
351
+ requestReconnect: Object.freeze({ count: 1, delay: 1e3 })
352
+ });
349
353
  var DISCOVERY_KINDS = /* @__PURE__ */ new Set([0, 3, 10002]);
350
354
  var APP_KINDS = /* @__PURE__ */ new Set([...NAPPLET_KINDS, 32267]);
351
355
  function asFilters(filters) {
@@ -591,6 +595,7 @@ function createAccountMailboxes(options) {
591
595
 
592
596
  // src/applesauce/relay-backend.ts
593
597
  import { lastValueFrom, toArray } from "rxjs";
598
+ import { createRelayPoolService } from "@kehto/services";
594
599
  async function publishAccepted(pool, relays2, event) {
595
600
  const responses = relays2.length > 0 ? await pool.publish(relays2, event) : [];
596
601
  const accepted = responses.filter((response) => response.ok).length;
@@ -610,10 +615,37 @@ function createAppletRelayBackend(pool, tiers) {
610
615
  async publish(event) {
611
616
  await publishAccepted(pool, selectRelayTier(tiers, [{ kinds: [event.kind] }]), event);
612
617
  },
618
+ async publishToRelays(relayUrls2, event) {
619
+ await publishAccepted(pool, [...relayUrls2], event);
620
+ },
613
621
  selectRelayTier: (filters) => selectRelayTier(tiers, filters),
614
622
  isAvailable: () => true
615
623
  };
616
624
  }
625
+ var UNCANCELLED = new AbortController().signal;
626
+ function kindOf(message) {
627
+ const kind = message.event?.kind;
628
+ return typeof kind === "number" ? kind : void 0;
629
+ }
630
+ function createAppletRelayService(pool, tiers) {
631
+ const inner = createRelayPoolService(createAppletRelayBackend(pool, tiers));
632
+ function planRelayOperation(windowId, message) {
633
+ const plan = inner.planRelayOperation(windowId, message);
634
+ const kind = kindOf(message);
635
+ const relay = message.relay;
636
+ const hinted = typeof relay === "string" && relay.length > 0;
637
+ if (plan.operation === "subscribe" || plan.operation === "query" || hinted || kind === void 0) return plan;
638
+ const relayUrls2 = Object.freeze([...new Set(selectRelayTier(tiers, [{ kinds: [kind] }]))]);
639
+ return Object.freeze({ operation: plan.operation, relayUrls: relayUrls2, localOnly: relayUrls2.length === 0 });
640
+ }
641
+ return {
642
+ ...inner,
643
+ planRelayOperation,
644
+ handleMessage(windowId, message, send) {
645
+ inner.executeRelayOperation(windowId, message, planRelayOperation(windowId, message), UNCANCELLED, send);
646
+ }
647
+ };
648
+ }
617
649
  function createDmRelayPool(pool, tiers) {
618
650
  return {
619
651
  subscribe(filters, callback, relayUrls2) {
@@ -652,20 +684,28 @@ function wrapAccountSigner(account) {
652
684
  return signer;
653
685
  }
654
686
  function createAuthHooks(accounts, consent) {
687
+ const signers = /* @__PURE__ */ new WeakMap();
688
+ function build(account, windowId) {
689
+ const signer = wrapAccountSigner(account);
690
+ if (windowId === void 0) return signer;
691
+ return {
692
+ ...signer,
693
+ async signEvent(template) {
694
+ await consent(windowId, template);
695
+ return account.signEvent(template);
696
+ }
697
+ };
698
+ }
655
699
  return {
656
700
  getUserPubkey: () => accounts.active?.pubkey ?? null,
657
701
  getSigner(windowId) {
658
702
  const account = accounts.active;
659
703
  if (!account || isReadOnlyAccount(account)) return null;
660
- const signer = wrapAccountSigner(account);
661
- if (windowId === void 0) return signer;
662
- return {
663
- ...signer,
664
- async signEvent(template) {
665
- await consent(windowId, template);
666
- return account.signEvent(template);
667
- }
668
- };
704
+ const byWindow = signers.get(account) ?? /* @__PURE__ */ new Map();
705
+ signers.set(account, byWindow);
706
+ const signer = byWindow.get(windowId) ?? build(account, windowId);
707
+ byWindow.set(windowId, signer);
708
+ return signer;
669
709
  }
670
710
  };
671
711
  }
@@ -964,22 +1004,30 @@ function settleManifestRequest(timing) {
964
1004
  const after = (messages, type, waitMs) => messages.pipe(filter((message) => message.type === type), take(1), switchMap2(() => timer2(waitMs)));
965
1005
  return (messages) => merge2(after(messages, "EVENT", timing.settleMs), after(messages, "EOSE", timing.patienceMs)).pipe(map4(() => true));
966
1006
  }
967
- async function askOnce(pool, relays2, filter3, waits) {
968
- const request = pool.request(relays2, asFilters([filter3]), { complete: settleManifestRequest(waits), timeout: waits.timeoutMs });
1007
+ function watchOpened(pool, relays2) {
1008
+ const relayOf = pool.relay;
1009
+ if (typeof relayOf !== "function") return { opened: () => true, stop: () => void 0 };
1010
+ let opened = false;
1011
+ const watching = relays2.map((url) => relayOf.call(pool, url).connected$.subscribe((connected) => void (opened ||= connected)));
1012
+ return { opened: () => opened, stop: () => watching.forEach((watch) => watch.unsubscribe()) };
1013
+ }
1014
+ async function askRelays(pool, relays2, filter3, waits) {
1015
+ const watch = watchOpened(pool, relays2);
1016
+ const request = pool.request(relays2, asFilters([filter3]), {
1017
+ complete: settleManifestRequest(waits),
1018
+ timeout: waits.timeoutMs,
1019
+ reconnect: { count: 1, delay: waits.retryDelayMs }
1020
+ });
969
1021
  try {
970
1022
  const events = await lastValueFrom3(request.pipe(toArray2()), { defaultValue: [] });
971
1023
  const newest2 = events.reduce((best, event) => best && best.created_at >= event.created_at ? best : event, void 0);
972
- return newest2 ? { newest: newest2, answered: true } : { answered: true };
973
- } catch (error) {
974
- return { answered: false, refused: error.name !== "TimeoutError" };
1024
+ return newest2 ? { newest: newest2, answered: true, opened: true } : { answered: watch.opened(), opened: watch.opened() };
1025
+ } catch {
1026
+ return { answered: false, opened: watch.opened() };
1027
+ } finally {
1028
+ watch.stop();
975
1029
  }
976
1030
  }
977
- async function askRelays(pool, relays2, filter3, waits) {
978
- const first = await askOnce(pool, relays2, filter3, waits);
979
- if (!first.refused) return first;
980
- await new Promise((resolve) => setTimeout(resolve, waits.retryDelayMs));
981
- return askOnce(pool, relays2, filter3, waits);
982
- }
983
1031
  async function fetchManifestEvent(pool, tiers, pointer, timing = {}) {
984
1032
  const config = tiers.get();
985
1033
  const first = dialable([...pointer.relays, ...config.apps]);
@@ -987,12 +1035,15 @@ async function fetchManifestEvent(pool, tiers, pointer, timing = {}) {
987
1035
  const waits = { ...MANIFEST_TIMING, ...timing };
988
1036
  const filter3 = filterFor(pointer);
989
1037
  let answered = rounds.length === 0;
1038
+ let opened = rounds.length === 0;
990
1039
  for (const relays2 of rounds) {
991
1040
  const asked = await askRelays(pool, relays2, filter3, waits);
992
1041
  if (asked.newest) return asked.newest;
993
1042
  answered ||= asked.answered;
1043
+ opened ||= asked.opened;
994
1044
  }
995
- throw new Error(answered ? "unavailable:manifest" : "unavailable:network");
1045
+ if (answered) throw new Error("unavailable:manifest");
1046
+ throw new Error(opened ? "unavailable:network" : "unavailable:unreachable");
996
1047
  }
997
1048
  async function defaultFetchBlob(sha256, servers, fetchImpl = fetch) {
998
1049
  for (const server of servers) {
@@ -1296,6 +1347,7 @@ function createGuardPipeline(options) {
1296
1347
  }
1297
1348
 
1298
1349
  // src/guard/runtime-rules.ts
1350
+ import { createFirewallState } from "@kehto/rate-limit/legacy";
1299
1351
  import { applyNappletRules } from "@kernlize/guard";
1300
1352
  var RUNTIME_FIREWALL_STORAGE_KEY = "kernl:firewall:v1";
1301
1353
  var RUNTIME_OP_CLASSES = Object.freeze({
@@ -1342,11 +1394,12 @@ function toGuardEvent(event, at) {
1342
1394
  }
1343
1395
  function createRuntimeFirewallHooks(options) {
1344
1396
  const now = options.now ?? Date.now;
1397
+ const legacyFirewall = createFirewallState({
1398
+ persist: (data) => options.storage.setItem(RUNTIME_FIREWALL_STORAGE_KEY, data),
1399
+ load: () => options.storage.getItem(RUNTIME_FIREWALL_STORAGE_KEY)
1400
+ });
1345
1401
  return {
1346
- firewallPersistence: {
1347
- persist: (data) => options.storage.setItem(RUNTIME_FIREWALL_STORAGE_KEY, data),
1348
- load: () => options.storage.getItem(RUNTIME_FIREWALL_STORAGE_KEY)
1349
- },
1402
+ legacyFirewall,
1350
1403
  onFirewallEvent: (event) => options.onEvent(toGuardEvent(event, now()))
1351
1404
  };
1352
1405
  }
@@ -2189,10 +2242,10 @@ function transportFor(options, signer) {
2189
2242
  return () => handle.unsubscribe();
2190
2243
  },
2191
2244
  async nostrPublish(event) {
2192
- const signed = await sign(event);
2193
- const results = await options.pool.publish(relays2(), signed).catch(() => []);
2245
+ const signed2 = await sign(event);
2246
+ const results = await options.pool.publish(relays2(), signed2).catch(() => []);
2194
2247
  if (!results.some((result) => result.ok)) throw new Error("unavailable:offline");
2195
- return signed;
2248
+ return signed2;
2196
2249
  }
2197
2250
  };
2198
2251
  }
@@ -2799,12 +2852,104 @@ function createBlossomUploader(options) {
2799
2852
  };
2800
2853
  }
2801
2854
 
2855
+ // src/applets/applet-config.ts
2856
+ var STORAGE_KEY4 = "applet-config:v1";
2857
+ function createAppletConfig(options) {
2858
+ const store = createNamespacedStore(options.storage, "kernl");
2859
+ const read = () => store.getJson(STORAGE_KEY4, {});
2860
+ return {
2861
+ getValues(windowId) {
2862
+ const applet = options.appletOf(windowId);
2863
+ return applet ? { ...read()[applet.key] } : {};
2864
+ },
2865
+ saveValues(windowId, values) {
2866
+ const applet = options.appletOf(windowId);
2867
+ if (applet) store.setJson(STORAGE_KEY4, { ...read(), [applet.key]: values });
2868
+ },
2869
+ openSettings(windowId, section, context) {
2870
+ const applet = options.appletOf(windowId);
2871
+ if (applet) options.present({ title: applet.title, ...section ? { section } : {}, context });
2872
+ }
2873
+ };
2874
+ }
2875
+
2876
+ // src/social/common-actions.ts
2877
+ import { getProfileContent as getProfileContent2, normalizeToPubkey, unixNow as unixNow5 } from "applesauce-core/helpers";
2878
+ var FOLLOWS2 = 3;
2879
+ var REACTION = 7;
2880
+ var REPORT = 1984;
2881
+ var reasonOf = (error) => error instanceof Error ? error.message : String(error);
2882
+ function followed(event) {
2883
+ return (event?.tags ?? []).filter((tag) => tag[0] === "p" && typeof tag[1] === "string").map((tag) => tag[1]);
2884
+ }
2885
+ function toPubkey(value) {
2886
+ return normalizeToPubkey(value) ?? void 0;
2887
+ }
2888
+ async function signed(options, windowId, template) {
2889
+ const signer = options.signer();
2890
+ if (!signer) return { ok: false, error: "denied:read-only" };
2891
+ try {
2892
+ await options.consent(windowId, template);
2893
+ const event = await signer.signEvent(template);
2894
+ await options.publish(event);
2895
+ options.store.add(event);
2896
+ return { ok: true, eventId: event.id, event };
2897
+ } catch (error) {
2898
+ return { ok: false, error: reasonOf(error) };
2899
+ }
2900
+ }
2901
+ async function changeFollows(options, windowId, pubkeys, add) {
2902
+ const self = options.pubkey();
2903
+ if (!self) return { ok: false, error: "denied:read-only" };
2904
+ const targets = pubkeys.map(toPubkey);
2905
+ if (targets.some((key) => key === void 0)) return { ok: false, error: "invalid:pubkey" };
2906
+ await options.loadFollows(self);
2907
+ const previous = options.store.getReplaceable(FOLLOWS2, self);
2908
+ const current = followed(previous);
2909
+ const next = add ? [.../* @__PURE__ */ new Set([...current, ...targets])] : current.filter((key) => !targets.includes(key));
2910
+ const others = (previous?.tags ?? []).filter((tag) => tag[0] !== "p");
2911
+ const tags = [...next.map((key) => ["p", key]), ...others];
2912
+ return signed(options, windowId, { kind: FOLLOWS2, created_at: Math.max(unixNow5(), (previous?.created_at ?? 0) + 1), tags, content: previous?.content ?? "" });
2913
+ }
2914
+ function createCommonActions(options) {
2915
+ return {
2916
+ async getProfile(target) {
2917
+ const pubkey = toPubkey(target);
2918
+ if (!pubkey) return { ok: false, pubkey: "", error: "invalid:pubkey" };
2919
+ const card = await options.profiles.settled(pubkey);
2920
+ const event = options.store.getReplaceable(0, pubkey);
2921
+ const content = event ? getProfileContent2(event) : void 0;
2922
+ if (!card.found || !content) return { ok: true, pubkey, profile: null };
2923
+ const { display_name: displayName, ...rest } = content;
2924
+ return { ok: true, pubkey, profile: { ...rest, ...displayName ? { displayName } : {} } };
2925
+ },
2926
+ async follows() {
2927
+ const self = options.pubkey();
2928
+ if (!self) return { ok: false, pubkeys: [], error: "denied:signed-out" };
2929
+ await options.loadFollows(self);
2930
+ return { ok: true, pubkeys: followed(options.store.getReplaceable(FOLLOWS2, self)) };
2931
+ },
2932
+ follow: (pubkeys, context) => changeFollows(options, context.windowId, pubkeys, true),
2933
+ unfollow: (pubkeys, context) => changeFollows(options, context.windowId, pubkeys, false),
2934
+ react(targetEventId, reaction, customEmojiHref, context) {
2935
+ const target = options.store.getEvent(targetEventId);
2936
+ const emoji = customEmojiHref && /^:[\w-]+:$/.test(reaction) ? [["emoji", reaction.slice(1, -1), customEmojiHref]] : [];
2937
+ const tags = [["e", targetEventId], ...target ? [["p", target.pubkey], ["k", String(target.kind)]] : [], ...emoji];
2938
+ return signed(options, context.windowId, { kind: REACTION, created_at: unixNow5(), tags, content: reaction });
2939
+ },
2940
+ report(target, reason, text2, context) {
2941
+ const tags = target.type === "event" ? [["e", target.id, reason], ...target.pubkey ? [["p", target.pubkey]] : []] : [["p", target.pubkey, reason]];
2942
+ return signed(options, context.windowId, { kind: REPORT, created_at: unixNow5(), tags, content: text2 });
2943
+ }
2944
+ };
2945
+ }
2946
+
2802
2947
  // src/kernl-network.ts
2803
- import { map as map7, takeUntil as takeUntil2 } from "rxjs";
2948
+ import { lastValueFrom as lastValueFrom7, map as map7, takeUntil as takeUntil2 } from "rxjs";
2804
2949
 
2805
2950
  // src/profiles/profiles.ts
2806
2951
  import { catchError as catchError3, distinctUntilChanged as distinctUntilChanged2, EMPTY as EMPTY3, endWith as endWith2, filter as filter2, firstValueFrom as firstValueFrom2, ignoreElements as ignoreElements2, map as map6, merge as merge3, Observable as Observable2, share, switchMap as switchMap4, take as take2, timer as timer4 } from "rxjs";
2807
- import { getDisplayName, getOutboxes as getOutboxes3, getProfileContent as getProfileContent2, getProfilePicture } from "applesauce-core/helpers";
2952
+ import { getDisplayName, getOutboxes as getOutboxes3, getProfileContent as getProfileContent3, getProfilePicture } from "applesauce-core/helpers";
2808
2953
  var PROFILE_KIND = 0;
2809
2954
  var MAILBOX_KIND = 10002;
2810
2955
  var KEEP_ALIVE_MS = 6e4;
@@ -2815,7 +2960,7 @@ function safePicture(event) {
2815
2960
  }
2816
2961
  function toProfileCard(pubkey, event) {
2817
2962
  const fallback = abbreviate(pubkey);
2818
- const content = event ? getProfileContent2(event) : void 0;
2963
+ const content = event ? getProfileContent3(event) : void 0;
2819
2964
  if (!event || !content) return Object.freeze({ pubkey, name: fallback, found: false });
2820
2965
  const name = getDisplayName(content)?.trim();
2821
2966
  const picture = safePicture(event);
@@ -2912,17 +3057,33 @@ function createKernlNetwork(options, parts) {
2912
3057
  });
2913
3058
  return { eventCache, replaceableLoader, profiles, directory, mailboxes, files, signer };
2914
3059
  }
3060
+ function commonActionsFor(parts, network, consent) {
3061
+ const { eventStore, pool, tiers, accounts } = parts;
3062
+ return createCommonActions({
3063
+ store: eventStore,
3064
+ profiles: network.profiles,
3065
+ pubkey: () => accounts.active?.pubkey,
3066
+ signer: network.signer,
3067
+ consent,
3068
+ publish: (event) => publishAccepted(pool, selectRelayTier(tiers, [{ kinds: [event.kind] }]), event),
3069
+ loadFollows: (pubkey) => lastValueFrom7(network.replaceableLoader({ kind: 3, pubkey, relays: lookupRelaysOf(tiers.get()) }), { defaultValue: void 0 }).then(
3070
+ () => void 0,
3071
+ () => void 0
3072
+ )
3073
+ });
3074
+ }
2915
3075
 
2916
3076
  // src/kernl-services.ts
2917
3077
  import { verifyEvent as verifyEvent4 } from "applesauce-core/helpers";
2918
3078
  import {
3079
+ createCommonService,
3080
+ createConfigService,
2919
3081
  createDmService,
2920
3082
  createIdentityService,
2921
3083
  createLinkService,
2922
3084
  createNotifyService,
2923
3085
  createOutboxService,
2924
3086
  createRelayPoolOutboxRouter,
2925
- createRelayPoolService,
2926
3087
  createResourceService,
2927
3088
  createThemeService,
2928
3089
  createUploadService
@@ -2965,11 +3126,16 @@ function resourceInitFor(deps, init) {
2965
3126
  const requester = requesterFor(deps, init.windowId);
2966
3127
  return init.headers ? { signal: init.signal, requester, headers: init.headers } : { signal: init.signal, requester };
2967
3128
  }
2968
- function identitySigner(auth) {
2969
- const signer = auth.getSigner();
2970
- if (signer) return signer;
2971
- const pubkey = auth.getUserPubkey?.() ?? null;
2972
- return pubkey === null ? null : { getPublicKey: () => pubkey };
3129
+ function createIdentitySigner(auth) {
3130
+ let view;
3131
+ return () => {
3132
+ const signer = auth.getSigner();
3133
+ if (signer) return signer;
3134
+ const pubkey = auth.getUserPubkey?.() ?? null;
3135
+ if (pubkey === null) return null;
3136
+ if (view?.pubkey !== pubkey) view = { pubkey, signer: { getPublicKey: () => pubkey } };
3137
+ return view.signer;
3138
+ };
2973
3139
  }
2974
3140
  function createOutbox(deps, identity) {
2975
3141
  const router = createRelayPoolOutboxRouter({
@@ -3018,8 +3184,8 @@ function createKernlServices(deps) {
3018
3184
  const dm = createDmService({ adapter: deps.profiles ? labelConversations(composite, deps.profiles) : composite });
3019
3185
  const resolve = createBridgeResourceResolver(deps.bridges);
3020
3186
  const registry = {
3021
- relay: createRelayPoolService(createAppletRelayBackend(deps.pool, deps.tiers)),
3022
- identity: createIdentityService({ getSigner: () => identitySigner(deps.auth), ...identity }),
3187
+ relay: createAppletRelayService(deps.pool, deps.tiers),
3188
+ identity: createIdentityService({ getSigner: createIdentitySigner(deps.auth), ...identity }),
3023
3189
  theme: theme.handler,
3024
3190
  notify: createNotifyService({
3025
3191
  present: ({ windowId, message }) => deps.host.notify({ title: message.title, windowId, tone: "info", ...message.body ? { body: message.body } : {} })
@@ -3032,11 +3198,12 @@ function createKernlServices(deps) {
3032
3198
  }
3033
3199
  }),
3034
3200
  resource: createResourceService({
3035
- fetch: (url, init) => resolve(url, resourceInitFor(deps, init)),
3036
- resolveIdentity: deps.resolveIdentity
3201
+ fetch: (url, init) => resolve(url, resourceInitFor(deps, init))
3037
3202
  }),
3038
3203
  dm,
3039
3204
  outbox: gateOutboxPublish(createOutbox(deps, identity), deps.consent),
3205
+ ...deps.config ? { config: createConfigService(deps.config).handler } : {},
3206
+ ...deps.common ? { common: createCommonService(deps.common) } : {},
3040
3207
  ...deps.uploader ? { upload: createUploadService({ uploader: deps.uploader, uploadInfo: { rails: [{ rail: "blossom", enabled: true }] } }) } : {}
3041
3208
  };
3042
3209
  return { registry, theme, dm };
@@ -3073,6 +3240,7 @@ function createShellAdapter(deps) {
3073
3240
  workerRelay: { getWorkerRelay: () => null },
3074
3241
  // kehto offers the upload domain only when both the service and this backend are present; kernl's uploads are Blossom (D-033).
3075
3242
  upload: { getUploader: () => deps.services.upload ? UPLOAD_BACKEND : null },
3243
+ common: { isAvailable: () => deps.services.common !== void 0 },
3076
3244
  crypto: { verifyEvent: (event) => Promise.resolve(verifyEvent5(event)) },
3077
3245
  link: { isAvailable: () => true },
3078
3246
  intent: { isAvailable: () => true },
@@ -3089,6 +3257,13 @@ function createShellAdapter(deps) {
3089
3257
 
3090
3258
  // src/kernl-lifecycle.ts
3091
3259
  import { originRegistry } from "@kehto/shell";
3260
+ function grantNarrowingReason(plan, record, baseline) {
3261
+ const { identity } = plan.summary;
3262
+ if (record.identity.dTag !== identity.dTag || record.identity.hash !== identity.hash) return void 0;
3263
+ if (record.blocked) return "blocked";
3264
+ const allowed = /* @__PURE__ */ new Set([...baseline, ...record.domains]);
3265
+ return plan.environment.capabilities.domains.some((domain) => !allowed.has(domain)) ? "grant-narrowed" : void 0;
3266
+ }
3092
3267
  function keyOf2(identity) {
3093
3268
  return `${identity.dTag}:${identity.hash}`;
3094
3269
  }
@@ -3139,7 +3314,7 @@ function createAppletLifecycle(context) {
3139
3314
  return planMount({ summary, indexHtml, adapter: context.adapter, guardProfile: pipeline.config.profile, windowId: `applet-${windowCounter}` });
3140
3315
  },
3141
3316
  mount(plan, frame) {
3142
- applyRuntimeFirewallRules(bridge.runtime.firewallState, pipeline.config, plan.summary.identity.dTag);
3317
+ applyRuntimeFirewallRules(context.firewall, pipeline.config, plan.summary.identity.dTag);
3143
3318
  const handle = mountApplet(plan, frame, {
3144
3319
  bridge,
3145
3320
  originRegistry,
@@ -3147,8 +3322,17 @@ function createAppletLifecycle(context) {
3147
3322
  onRevoked: (windowId, reason) => context.host.onRevoked(windowId, reason)
3148
3323
  });
3149
3324
  handles.set(plan.windowId, handle);
3325
+ const narrowed = context.grants.changes$.subscribe((record) => {
3326
+ const reason = grantNarrowingReason(plan, record, context.grants.baselineDomains());
3327
+ if (!reason) return;
3328
+ handle.revoked(reason);
3329
+ bridge.revokeNapplet(plan.windowId, "host");
3330
+ });
3331
+ context.subscriptions.add(narrowed);
3150
3332
  context.subscriptions.add(handle.status$.subscribe((status) => {
3151
- if (status === "closed" || status === "revoked") handles.delete(plan.windowId);
3333
+ if (status !== "closed" && status !== "revoked") return;
3334
+ handles.delete(plan.windowId);
3335
+ narrowed.unsubscribe();
3152
3336
  }));
3153
3337
  return handle;
3154
3338
  },
@@ -3168,11 +3352,10 @@ import { createGuardConfig as createGuardConfig2, describeMitigations } from "@k
3168
3352
 
3169
3353
  // src/kernl-intents.ts
3170
3354
  import { Subscription } from "rxjs";
3171
- import { originRegistry as originRegistry2 } from "@kehto/shell";
3172
3355
  import { createIntentService } from "@kehto/services";
3173
3356
 
3174
3357
  // src/intents/defaults.ts
3175
- import { lastValueFrom as lastValueFrom7, Subject as Subject3, takeUntil as takeUntil3, timer as timer5, toArray as toArray5 } from "rxjs";
3358
+ import { lastValueFrom as lastValueFrom8, Subject as Subject3, takeUntil as takeUntil3, timer as timer5, toArray as toArray5 } from "rxjs";
3176
3359
  import { verifyEvent as verifyEvent6 } from "applesauce-core/helpers";
3177
3360
 
3178
3361
  // src/intents/preferences.ts
@@ -3288,7 +3471,7 @@ function createHandlerDefaults(options) {
3288
3471
  loadedFor = pubkey;
3289
3472
  if (!pubkey) return;
3290
3473
  const request = options.pool.request([...preferenceRelays(options.tiers)], asFilters([{ kinds: [HANDLER_PREFERENCES_KIND], authors: [pubkey] }]));
3291
- const events = await lastValueFrom7(request.pipe(takeUntil3(timer5(LOAD_TIMEOUT_MS)), toArray5()), { defaultValue: [] }).catch(() => []);
3474
+ const events = await lastValueFrom8(request.pipe(takeUntil3(timer5(LOAD_TIMEOUT_MS)), toArray5()), { defaultValue: [] }).catch(() => []);
3292
3475
  for (const [archetype, event] of newestPerArchetype(events, pubkey)) {
3293
3476
  published.set(archetype, event);
3294
3477
  changes$.next(archetype);
@@ -3335,7 +3518,7 @@ function createIntentDelivery(options) {
3335
3518
  // src/intents/installed.ts
3336
3519
  import { BehaviorSubject as BehaviorSubject7 } from "rxjs";
3337
3520
  import { manifestToIntentCatalogEntry } from "@kehto/services";
3338
- var STORAGE_KEY4 = "installed:v1";
3521
+ var STORAGE_KEY5 = "installed:v1";
3339
3522
  function isInstalled(value) {
3340
3523
  if (typeof value !== "object" || value === null) return false;
3341
3524
  const row = value;
@@ -3355,10 +3538,10 @@ function toCatalogEntry2(applet) {
3355
3538
  }
3356
3539
  function createInstalledApplets(storage, now = Date.now) {
3357
3540
  const store = createNamespacedStore(storage, "kernl");
3358
- const stored = store.getJson(STORAGE_KEY4, []);
3541
+ const stored = store.getJson(STORAGE_KEY5, []);
3359
3542
  const changes$ = new BehaviorSubject7(Object.freeze(Array.isArray(stored) ? stored.filter(isInstalled) : []));
3360
3543
  const commit = (next) => {
3361
- store.setJson(STORAGE_KEY4, next);
3544
+ store.setJson(STORAGE_KEY5, next);
3362
3545
  changes$.next(Object.freeze([...next]));
3363
3546
  };
3364
3547
  return {
@@ -3512,10 +3695,9 @@ function createKernlIntents(deps) {
3512
3695
  findWindow: (catalogId) => [...handles.values()].find((handle) => handle.summary.manifest.catalogId === catalogId)?.windowId,
3513
3696
  openApplet: async (address) => host.openApplet?.(address),
3514
3697
  ...host.focusApplet ? { focus: host.focusApplet.bind(host) } : {},
3515
- // kehto's ACL gives `intent.deliver` no recipient capability, so the runtime's recipient-checked
3516
- // send refuses it. Like kehto's own Paja host, the delivery goes over the target's bound port,
3517
- // and only to a live session that holds the receiving grant (DECISIONS.md D-026).
3518
- send: (windowId, message) => context?.hasCapability(windowId, "intent:read") === true && originRegistry2.postToNapplet(windowId, message),
3698
+ // The runtime's recipient gate maps `intent.deliver` to `intent:read` since @kehto/acl 0.20.6,
3699
+ // so delivery goes through it to a live, unblocked, granted target (DECISIONS.md D-037).
3700
+ send: (windowId, message) => context?.sendToEligibleNapplet(windowId, message) === true,
3519
3701
  ...deps.retry ? { retry: deps.retry } : {}
3520
3702
  });
3521
3703
  const router = createIntentRouter({
@@ -3551,7 +3733,7 @@ function createKernlIntents(deps) {
3551
3733
  }
3552
3734
 
3553
3735
  // src/catalog/fetch.ts
3554
- import { auditTime as auditTime2, catchError as catchError4, EMPTY as EMPTY4, from, lastValueFrom as lastValueFrom8, map as map8, merge as merge4, mergeAll, scan, share as share2, takeUntil as takeUntil4, tap, timer as timer6 } from "rxjs";
3736
+ import { auditTime as auditTime2, catchError as catchError4, EMPTY as EMPTY4, from, lastValueFrom as lastValueFrom9, map as map8, merge as merge4, mergeAll, scan, share as share2, takeUntil as takeUntil4, tap, timer as timer6 } from "rxjs";
3555
3737
  import { getSeenRelays } from "applesauce-core/helpers";
3556
3738
  import { NAPPLET_KIND_NAMED, NAPPLET_KIND_ROOT } from "@kehto/nip/5d";
3557
3739
 
@@ -3619,7 +3801,7 @@ function streamCatalog(pool, tiers, options = {}) {
3619
3801
  return merge4(nothingYet, lists);
3620
3802
  }
3621
3803
  async function loadCatalog(pool, tiers, options = {}) {
3622
- return lastValueFrom8(streamCatalog(pool, tiers, options), { defaultValue: Object.freeze([]) });
3804
+ return lastValueFrom9(streamCatalog(pool, tiers, options), { defaultValue: Object.freeze([]) });
3623
3805
  }
3624
3806
 
3625
3807
  // src/kernl.ts
@@ -3629,11 +3811,11 @@ function toSession(account, card) {
3629
3811
  const label = named ?? (card?.found ? card.name : abbreviate(account.pubkey));
3630
3812
  return { accountId: account.id, pubkey: account.pubkey, label, readOnly: isReadOnlyAccount(account) };
3631
3813
  }
3632
- function followShellState({ pipeline, bridge, handles, accounts, session$, profiles, mailboxes, tiers }) {
3814
+ function followShellState({ pipeline, firewall, bridge, handles, accounts, session$, profiles, mailboxes, tiers }) {
3633
3815
  const subscriptions = new Subscription2();
3634
3816
  subscriptions.add(pipeline.profile$.subscribe(() => {
3635
- applyRuntimeFirewallProfile(bridge.runtime.firewallState, pipeline.config);
3636
- for (const handle of handles.values()) applyRuntimeFirewallRules(bridge.runtime.firewallState, pipeline.config, handle.summary.identity.dTag);
3817
+ applyRuntimeFirewallProfile(firewall, pipeline.config);
3818
+ for (const handle of handles.values()) applyRuntimeFirewallRules(firewall, pipeline.config, handle.summary.identity.dTag);
3637
3819
  }));
3638
3820
  subscriptions.add(accounts.active$.subscribe((account) => bridge.publishIdentityChanged(account?.pubkey ?? "")));
3639
3821
  const sessions = accounts.active$.pipe(switchMap5((account) => account ? profiles.card$(account.pubkey).pipe(map9((card) => toSession(account, card))) : of3(null)));
@@ -3699,8 +3881,12 @@ function registriesFor(options, parts) {
3699
3881
  bridges: options.bridges ?? createDefaultBridges({ handoff: (uri) => host.openLink(uri), ...options.torrent ? { torrent: options.torrent } : {} })
3700
3882
  };
3701
3883
  }
3884
+ function appletOf(handles, windowId) {
3885
+ const summary = handles.get(windowId)?.summary;
3886
+ return summary && { key: summary.manifest.catalogId, title: summary.title };
3887
+ }
3702
3888
  function tearDown(parts) {
3703
- for (const handle of [...parts.handles.values()]) handle.close();
3889
+ for (const handle of parts.handles.values()) handle.close();
3704
3890
  parts.subscriptions.unsubscribe();
3705
3891
  parts.destroyed$.next();
3706
3892
  parts.network.directory.stop();
@@ -3716,7 +3902,7 @@ function createKernl(options) {
3716
3902
  const ownsPool = !options.pool;
3717
3903
  const ownsMessaging = !options.messaging;
3718
3904
  const eventStore = options.eventStore ?? new EventStore();
3719
- const pool = options.pool ?? new RelayPool();
3905
+ const pool = options.pool ?? new RelayPool(SHELL_RELAY_OPTIONS);
3720
3906
  const accounts = options.accounts ?? createKernlAccounts(host.storage);
3721
3907
  const tiers = createRelayTiers(host.storage, options.relays ?? {});
3722
3908
  const { messaging, bridges } = registriesFor(options, { eventStore, pool, tiers, accounts });
@@ -3754,6 +3940,8 @@ function createKernl(options) {
3754
3940
  bridges,
3755
3941
  messaging,
3756
3942
  profiles,
3943
+ ...host.presentSettings ? { config: createAppletConfig({ storage: host.storage, appletOf: (windowId) => appletOf(handles, windowId), present: host.presentSettings.bind(host) }) } : {},
3944
+ common: commonActionsFor({ eventStore, pool, tiers, accounts }, { profiles, replaceableLoader, signer }, consent),
3757
3945
  uploader: createBlossomUploader({
3758
3946
  servers: () => files.current(),
3759
3947
  signer,
@@ -3767,6 +3955,11 @@ function createKernl(options) {
3767
3955
  });
3768
3956
  const intents = createKernlIntents({ host, pool, tiers, accounts, handles, ...options.intentRetry ? { retry: options.intentRetry } : {} });
3769
3957
  services.registry.intent = intents.handler;
3958
+ const runtimeFirewall = createRuntimeFirewallHooks({
3959
+ storage: host.storage,
3960
+ onEvent: (event) => guardEvents$.next(event),
3961
+ ...host.now ? { now: host.now.bind(host) } : {}
3962
+ });
3770
3963
  const adapter = createShellAdapter({
3771
3964
  pool,
3772
3965
  tiers,
@@ -3777,22 +3970,19 @@ function createKernl(options) {
3777
3970
  onNappletRevoked: ({ windowId, reason }) => handles.get(windowId)?.revoked(reason),
3778
3971
  filterNappletMessage: (windowId, message) => pipeline.observe(windowId, identityOf(windowId)?.dTag ?? "unknown", message),
3779
3972
  getFocusContext: (windowId) => ({ focused: pipeline.getVisibility(windowId).focused }),
3780
- runtimeFirewall: createRuntimeFirewallHooks({
3781
- storage: host.storage,
3782
- onEvent: (event) => guardEvents$.next(event),
3783
- ...host.now ? { now: host.now.bind(host) } : {}
3784
- })
3973
+ runtimeFirewall
3785
3974
  });
3786
3975
  const bridge = createShellBridge(adapter);
3787
3976
  grants = createGrants({ acl: bridge.runtime.aclState, storage: host.storage, availableDomains: () => buildShellCapabilities(adapter).domains });
3788
3977
  bridge.registerConsentHandler(createConsentHandler(host, lookupBefore, identityOf));
3789
- subscriptions.add(followShellState({ pipeline, bridge, handles, accounts, session$, profiles, mailboxes, tiers }));
3978
+ subscriptions.add(followShellState({ pipeline, firewall: runtimeFirewall.legacyFirewall, bridge, handles, accounts, session$, profiles, mailboxes, tiers }));
3790
3979
  const lifecycle = createAppletLifecycle({
3791
3980
  pool,
3792
3981
  tiers,
3793
3982
  adapter,
3794
3983
  bridge,
3795
3984
  pipeline,
3985
+ firewall: runtimeFirewall.legacyFirewall,
3796
3986
  grants,
3797
3987
  installed: intents.installed,
3798
3988
  host,
@@ -3923,6 +4113,7 @@ export {
3923
4113
  PLAINTEXT_KEY_ACCOUNT_TYPES,
3924
4114
  RUNTIME_FIREWALL_STORAGE_KEY,
3925
4115
  RUNTIME_OP_CLASSES,
4116
+ SHELL_RELAY_OPTIONS,
3926
4117
  UNKNOWN_CURRENT_VERSION,
3927
4118
  abbreviate,
3928
4119
  addressOf,
@@ -3935,14 +4126,18 @@ export {
3935
4126
  capabilitiesForDomains,
3936
4127
  catalogIdForRef,
3937
4128
  catalogRelays,
4129
+ commonActionsFor,
3938
4130
  connectEventCache,
3939
4131
  createAccountFileServers,
3940
4132
  createAccountMailboxes,
4133
+ createAppletConfig,
3941
4134
  createAppletLifecycle,
3942
4135
  createAppletRelayBackend,
4136
+ createAppletRelayService,
3943
4137
  createAuthHooks,
3944
4138
  createBlossomUploader,
3945
4139
  createColumnsLayout,
4140
+ createCommonActions,
3946
4141
  createConsentHandler,
3947
4142
  createDefaultBridges,
3948
4143
  createDefaultLayouts,
@@ -4000,6 +4195,7 @@ export {
4000
4195
  floatingLayout,
4001
4196
  fromEventDatabase,
4002
4197
  fuzzyScore,
4198
+ grantNarrowingReason,
4003
4199
  installCryptoFallback,
4004
4200
  isCorruptionError,
4005
4201
  isDestructiveKind,