@kernlize/core 0.8.0 → 0.11.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.d.ts +621 -101
- package/dist/index.js +1049 -151
- package/dist/index.js.map +1 -1
- package/package.json +19 -19
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/persistence/store.ts","../src/relays/tiers.ts","../src/relays/publish-outcome.ts","../src/relays/directory.ts","../src/relays/mailboxes.ts","../src/applesauce/relay-hooks.ts","../src/applesauce/relay-backend.ts","../src/applesauce/auth-hooks.ts","../src/applesauce/identity-providers.ts","../src/applesauce/accounts.ts","../src/applets/pointer.ts","../src/applets/builtin.ts","../src/applets/resolve.ts","../src/catalog/entry.ts","../src/applets/plan.ts","../src/applets/mount.ts","../src/guard/pipeline.ts","../src/guard/runtime-rules.ts","../src/grants/domain-capabilities.ts","../src/grants/grants.ts","../src/consent/describe-change.ts","../src/consent/handler.ts","../src/messaging/default-registry.ts","../src/messaging/availability.ts","../src/messaging/private-backend.ts","../src/messaging/signer-backend.ts","../src/messaging/conversation-store.ts","../src/messaging/inbox-relays.ts","../src/messaging/legacy-backend.ts","../src/messaging/ratchet-backend.ts","../src/messaging/ratchet-storage.ts","../src/messaging/group-backend.ts","../src/messaging/group-network.ts","../src/messaging/group-session.ts","../src/messaging/group-storage.ts","../src/bridges/default-registry.ts","../src/messaging/label-conversations.ts","../src/files/file-servers.ts","../src/files/uploader.ts","../src/kernl-network.ts","../src/profiles/profiles.ts","../src/kernl-services.ts","../src/kernl-adapter.ts","../src/kernl-lifecycle.ts","../src/kernl.ts","../src/kernl-intents.ts","../src/intents/defaults.ts","../src/intents/preferences.ts","../src/intents/delivery.ts","../src/intents/installed.ts","../src/intents/router.ts","../src/catalog/fetch.ts","../src/catalog/withdrawn.ts","../src/catalog/search.ts"],"sourcesContent":["/**\n * Opinionated shell composition over kehto and applesauce: adapters, applet\n * resolution and mounting, grants, consent summaries, layouts and persistence.\n *\n * @packageDocumentation\n */\nimport { renderNappletFramePolicyMeta } from '@kehto/shell';\n\n/**\n * The npm package name, shared by both registry builds.\n *\n * @example\n * ```ts\n * PACKAGE_NAME; // '@kernlize/core'\n * ```\n */\nexport const PACKAGE_NAME = '@kernlize/core';\n\n/**\n * The `<meta>` element the host page puts in its `<head>` so applet frames can\n * never navigate away from their verified `srcdoc`. Rendered once by kehto.\n *\n * @example\n * ```ts\n * document.head.insertAdjacentHTML('afterbegin', KERNL_FRAME_POLICY_META);\n * ```\n */\nexport const KERNL_FRAME_POLICY_META: string = renderNappletFramePolicyMeta();\n\nexport type * from './types.js';\n\nexport { createNamespacedStore, type NamespacedStore } from './persistence/store.js';\nexport { DEFAULT_RELAY_TIERS, createRelayTiers } from './relays/tiers.js';\nexport type { TierMap } from './relays/tiers.js';\nexport { describeOutcome, relayUrls, summarizePublish, toRelayUrl, type PublishAnswer, type PublishOutcome } from './relays/publish-outcome.js';\nexport {\n DEFAULT_MONITOR_RELAYS,\n DEFAULT_SUGGESTIONS,\n createRelayDirectory,\n type DirectoryPool,\n type RelayDirectory,\n type RelayDirectoryOptions,\n type RelayListing,\n type SuggestOptions,\n type SuggestPurpose,\n} from './relays/directory.js';\nexport {\n createAccountMailboxes,\n mailboxTags,\n mailboxesFromEvent,\n type AccountMailboxes,\n type AccountMailboxesOptions,\n type MailboxPool,\n type MailboxSigner,\n type MailboxState,\n type Mailboxes,\n} from './relays/mailboxes.js';\n\nexport {\n createRelayPoolHooks,\n createRelayPoolLike,\n selectRelayTier,\n subscribeWithEose,\n type ApplesaucePool,\n type EoseSubscription,\n} from './applesauce/relay-hooks.js';\nexport { createAppletRelayBackend, createDmRelayPool, createOutboxRelayPool, publishAccepted, type OutboxRelayPoolLike } from './applesauce/relay-backend.js';\nexport { createAuthHooks, isReadOnlyAccount, wrapAccountSigner } from './applesauce/auth-hooks.js';\nexport {\n createIdentityProviders,\n createReplaceableLoader,\n lookupRelaysOf,\n type IdentityProfile,\n type IdentityProviderOptions,\n type IdentityProviders,\n type RelayPermissions,\n} from './applesauce/identity-providers.js';\nexport { KernlAccountManager, PLAINTEXT_KEY_ACCOUNT_TYPES, createKernlAccounts } from './applesauce/accounts.js';\n\nexport { decodePointer } from './applets/pointer.js';\nexport { BUILTIN_PUBLISHER, builtinAddress, resolveBuiltin } from './applets/builtin.js';\nexport {\n BLOB_TIMEOUT_MS,\n MANIFEST_TIMING,\n defaultFetchBlob,\n fetchManifestEvent,\n openDefaultArtifactCache,\n resolveApplet,\n summarize,\n type ManifestTiming,\n type PublishedPointer,\n type ResolveAppletOptions,\n type ResolvedApplet,\n} from './applets/resolve.js';\nexport { planMount, type PlanMountOptions } from './applets/plan.js';\nexport { CONTROLLER_DENY_POLICY, mountApplet, type MountDeps, type MountGuardHooks, type MountedApplet } from './applets/mount.js';\n\nexport {\n createGuardPipeline,\n type GuardPipeline,\n type GuardPipelineOptions,\n type PipelineDisposition,\n type WindowResolution,\n} from './guard/pipeline.js';\nexport {\n RUNTIME_FIREWALL_STORAGE_KEY,\n RUNTIME_OP_CLASSES,\n applyRuntimeFirewallProfile,\n applyRuntimeFirewallRules,\n createRuntimeFirewallHooks,\n runtimeFirewallRules,\n toGuardEvent,\n type RuntimeFirewallHooks,\n type RuntimeFirewallHooksOptions,\n type RuntimeFirewallRules,\n type RuntimeFirewallState,\n type RuntimeRateRule,\n} from './guard/runtime-rules.js';\n\nexport { BASELINE_DOMAINS, DOMAIN_CAPABILITIES, capabilitiesForDomain, capabilitiesForDomains } from './grants/domain-capabilities.js';\nexport { createEnvironmentResolver, createGrants, type GrantsOptions, type KernlGrants } from './grants/grants.js';\n\nexport { abbreviate, describeChange, isDestructiveKind } from './consent/describe-change.js';\nexport {\n CURRENT_VERSION_TIMEOUT_MS,\n UNKNOWN_CURRENT_VERSION,\n createConsentHandler,\n createSigningConsent,\n lookupReplaceable,\n type LookupBefore,\n type LookupReplaceableOptions,\n type ResolveAppletIdentity,\n type SigningConsent,\n type SigningConsentOptions,\n type SigningTemplate,\n} from './consent/handler.js';\n\nexport {\n createColumnsLayout,\n createDefaultLayouts,\n createDwindleLayout,\n createLayoutRegistry,\n createMasterStackLayout,\n createWindowManager,\n floatingLayout,\n type LayoutChoice,\n type LayoutEntry,\n type LayoutOptions,\n type LayoutRegistry,\n type LayoutStrategy,\n type ManagedWindow,\n type MasterStackOptions,\n type Rect,\n type VisibilityTarget,\n type WindowManager,\n type WindowManagerOptions,\n type WindowManagerState,\n type WindowPlacement,\n type WindowSize,\n type WindowState,\n} from './wm/index.js';\nexport { createFallbackSubtle, installCryptoFallback, randomUuidFallback, renderRandomUuidFallbackScript, type CryptoFallbackReport, type CryptoScope } from './crypto/index.js';\nexport {\n attachEventCache,\n createEventCache,\n createIndexedDbCacheAdapter,\n createMemoryCacheAdapter,\n createSqliteOpfsCacheAdapter,\n defaultWebCacheAdapters,\n fromEventDatabase,\n isCorruptionError,\n openEventCache,\n type AttachedEventCache,\n type AttachEventCacheOptions,\n type CacheRecoveryEvent,\n type EventCache,\n type EventCacheAdapter,\n type EventRecords,\n type FilenameStorage,\n type IndexedDbCacheOptions,\n type LockManagerLike,\n type OpenEventCacheOptions,\n type SqliteDriver,\n type SqliteFiles,\n type SqliteOpfsOptions,\n type SqlStatement,\n type SqlValue,\n connectEventCache,\n type ConnectedEventCache,\n type EventCacheOpener,\n} from './cache/index.js';\n\nexport { createDefaultMessaging, type DefaultMessagingOptions } from './messaging/default-registry.js';\nexport { MESSAGING_UNAVAILABLE_REASONS, messagingSigner, signerAvailability, type MessagingEncryption } from './messaging/availability.js';\nexport type { SignerMessagingOptions } from './messaging/signer-backend.js';\nexport { createPrivateMessagesBackend } from './messaging/private-backend.js';\nexport { createLegacyMessagesBackend } from './messaging/legacy-backend.js';\nexport { createRatchetMessagesBackend, type RatchetMessagingOptions } from './messaging/ratchet-backend.js';\nexport { createGroupMessagesBackend, type GroupMessagingOptions } from './messaging/group-backend.js';\nexport { createSealedGroupStore, type SealedGroupStoreOptions } from './messaging/group-storage.js';\nexport { createGroupNetwork } from './messaging/group-network.js';\nexport type { InboxRelays } from './messaging/inbox-relays.js';\nexport { createSealedRatchetStorage, type SealedRatchetStorageOptions } from './messaging/ratchet-storage.js';\nexport { createDefaultBridges, type DefaultBridgesOptions } from './bridges/default-registry.js';\n\nexport { labelConversations } from './messaging/label-conversations.js';\nexport { createAccountFileServers, DEFAULT_FILE_SERVERS, fileServersFromEvent, fileServerTags, type AccountFileServers, type AccountFileServersOptions, type FileServerState } from './files/file-servers.js';\nexport { askUploadConsent, createBlossomUploader, describeUpload, sizeWords, type BlossomUploaderOptions, type MultiServerUpload, type UploadDetails } from './files/uploader.js';\nexport { createKernlNetwork, type KernlNetwork, type KernlNetworkParts } from './kernl-network.js';\nexport { LINK_PROTOCOLS, createKernlServices, isTheme, resourceInitFor, type KernlServiceDeps, type KernlServices } from './kernl-services.js';\nexport { createShellAdapter, type ShellAdapterDeps } from './kernl-adapter.js';\nexport { createAppletLifecycle, resolveWindow, type AppletLifecycle, type LifecycleContext } from './kernl-lifecycle.js';\nexport { createKernl, toSession } from './kernl.js';\nexport { createProfiles, toProfileCard, type ProfileCard, type ProfileLoader, type ProfilePointer, type Profiles, type ProfilesOptions } from './profiles/profiles.js';\nexport { addressOf, newestEntries, toCatalogEntry, type CatalogEntry } from './catalog/entry.js';\nexport { CATALOG_EMIT_MS, CATALOG_LIMIT, CATALOG_SETTLE_MS, CATALOG_TIMEOUT_MS, catalogRelays, loadCatalog, streamCatalog, type LoadCatalogOptions } from './catalog/fetch.js';\nexport { fuzzyScore, popularTopics, searchCatalog, type CatalogQuery, type TopicCount } from './catalog/search.js';\nexport { createInstalledApplets, type InstallableApplet, type InstalledApplet, type InstalledApplets, type InstalledContract } from './intents/installed.js';\nexport {\n HANDLER_PREFERENCES_KIND,\n catalogIdForRef,\n parseHandlerPreferences,\n preferenceTemplate,\n preferredHandlers,\n refForCatalogId,\n type HandlerPreferences,\n} from './intents/preferences.js';\nexport { createHandlerDefaults, preferenceRelays, type HandlerDefaults, type HandlerDefaultsOptions, type PreferenceSigner } from './intents/defaults.js';\nexport { createIntentRouter, type IntentRouter, type IntentRouterOptions } from './intents/router.js';\nexport { DELIVERY_RETRY, createIntentDelivery, type IntentDeliveryOptions } from './intents/delivery.js';\nexport { createKernlIntents, type KernlIntentDeps, type KernlIntents } from './kernl-intents.js';\n","import type { StorageLike } from '../types.js';\n\n/** A prefixed JSON view over a {@link StorageLike}. */\nexport interface NamespacedStore {\n /** Read and parse a value; `fallback` when the key is absent or unreadable. */\n getJson<T>(key: string, fallback: T): T;\n /** Serialise and write a value. */\n setJson(key: string, value: unknown): void;\n remove(key: string): void;\n}\n\ntype ParsedJson = { readonly ok: true; readonly value: unknown } | { readonly ok: false };\n\nfunction parseJson(raw: string): ParsedJson {\n try {\n return { ok: true, value: JSON.parse(raw) };\n } catch {\n return { ok: false };\n }\n}\n\n/**\n * Create a store that keeps every kernl key under one prefix, so the host's\n * storage can also hold kehto's and the app's own keys without collisions.\n *\n * Corrupt JSON reads as the fallback rather than throwing: persisted state is\n * a convenience, and a damaged value must never stop the shell from booting.\n *\n * @param storage - Synchronous key-value storage; `localStorage` or a Map-backed fake.\n * @param prefix - Namespace prepended to every key, for example `kernl`.\n * @returns A namespaced JSON store.\n * @example\n * ```ts\n * const store = createNamespacedStore(localStorage, 'kernl');\n * store.setJson('relays:v1', { apps: ['wss://relay.napplet.soy'] });\n * store.getJson('relays:v1', {}); // { apps: [...] }\n * ```\n */\nexport function createNamespacedStore(storage: StorageLike, prefix: string): NamespacedStore {\n const keyFor = (key: string): string => `${prefix}:${key}`;\n return {\n getJson<T>(key: string, fallback: T): T {\n const raw = storage.getItem(keyFor(key));\n if (raw === null) return fallback;\n const parsed = parseJson(raw);\n return parsed.ok ? (parsed.value as T) : fallback;\n },\n setJson(key, value) {\n storage.setItem(keyFor(key), JSON.stringify(value));\n },\n remove(key) {\n storage.removeItem(keyFor(key));\n },\n };\n}\n","import { BehaviorSubject } from 'rxjs';\nimport type { RelayTier, RelayTiers, StorageLike } from '../types.js';\nimport { createNamespacedStore } from '../persistence/store.js';\n\n/** Relay URLs per tier, frozen. */\nexport type TierMap = Readonly<Record<RelayTier, readonly string[]>>;\n\n/**\n * Where the shell looks when the user has configured nothing.\n *\n * @example\n * ```ts\n * DEFAULT_RELAY_TIERS.apps; // ['wss://relay.napplet.soy', 'wss://relay.ditto.pub', 'wss://relay.nostr.com']\n * DEFAULT_RELAY_TIERS.outbox; // []\n * ```\n */\nexport const DEFAULT_RELAY_TIERS: TierMap = Object.freeze({\n discovery: ['wss://purplepag.es', 'wss://relay.nos.social'],\n // The catalogues the two public napplet stores read; together with `super` they hold every napplet either lists.\n apps: ['wss://relay.napplet.soy', 'wss://relay.ditto.pub', 'wss://relay.nostr.com'],\n outbox: [],\n super: ['wss://relay.damus.io', 'wss://nos.lol', 'wss://relay.primal.net'],\n});\n\nconst TIERS: readonly RelayTier[] = ['discovery', 'apps', 'outbox', 'super'];\nconst STORAGE_KEY = 'relays:v1';\n\nfunction freeze(tiers: Record<RelayTier, readonly string[]>): TierMap {\n return Object.freeze({\n discovery: Object.freeze([...tiers.discovery]),\n apps: Object.freeze([...tiers.apps]),\n outbox: Object.freeze([...tiers.outbox]),\n super: Object.freeze([...tiers.super]),\n });\n}\n\nfunction merge(base: TierMap, overrides: Partial<Record<RelayTier, readonly string[]>>): TierMap {\n const next = { ...base } as Record<RelayTier, readonly string[]>;\n for (const tier of TIERS) {\n const value = overrides[tier];\n if (Array.isArray(value)) next[tier] = value.filter((url) => typeof url === 'string');\n }\n return freeze(next);\n}\n\nfunction assertRelayUrl(url: string): void {\n if (!/^wss?:\\/\\/\\S+$/.test(url)) throw new Error('invalid:relay-url');\n}\n\n/**\n * Create the relay tier configuration the shell and kehto both read.\n *\n * kehto's `RelayConfigHooks` knows `discovery`, `super` and `outbox`; kernl adds\n * `apps`, the tier that serves applet manifests. The configuration is persisted\n * at `kernl:relays:v1` and `changes$` replays the current value to new\n * subscribers so UI and adapters can share one source.\n *\n * @param storage - Where the user's relay choices are persisted.\n * @param defaults - Per-tier overrides applied over {@link DEFAULT_RELAY_TIERS} when nothing is persisted.\n * @returns The tier configuration.\n * @example\n * ```ts\n * const tiers = createRelayTiers(localStorage, { apps: ['wss://relay.example'] });\n * tiers.add('outbox', 'wss://relay.mine');\n * tiers.get().outbox; // ['wss://relay.mine']\n * ```\n */\nexport function createRelayTiers(storage: StorageLike, defaults: Partial<Record<RelayTier, readonly string[]>> = {}): RelayTiers {\n const store = createNamespacedStore(storage, 'kernl');\n const persisted = store.getJson<Partial<Record<RelayTier, readonly string[]>> | null>(STORAGE_KEY, null);\n const initial = persisted ? merge(DEFAULT_RELAY_TIERS, persisted) : merge(DEFAULT_RELAY_TIERS, defaults);\n const changes$ = new BehaviorSubject<TierMap>(initial);\n\n const update = (tier: RelayTier, urls: readonly string[]): void => {\n const next = freeze({ ...changes$.value, [tier]: urls });\n store.setJson(STORAGE_KEY, next);\n changes$.next(next);\n };\n\n return {\n get: () => changes$.value,\n add(tier, url) {\n assertRelayUrl(url);\n const current = changes$.value[tier];\n if (!current.includes(url)) update(tier, [...current, url]);\n },\n set(tier, urls) {\n urls.forEach(assertRelayUrl);\n const next = [...new Set(urls)];\n const current = changes$.value[tier];\n if (next.length !== current.length || next.some((url, index) => url !== current[index])) update(tier, next);\n },\n remove(tier, url) {\n const current = changes$.value[tier];\n if (current.includes(url)) update(tier, current.filter((entry) => entry !== url));\n },\n changes$,\n };\n}\n","import { normalizeRelayUrl } from 'applesauce-core/helpers';\n\n/** What came of one publish across several servers. */\nexport interface PublishOutcome {\n /** Servers that accepted the event, normalised, in the order they answered. */\n readonly accepted: readonly string[];\n /** Servers that refused it, each with the server's own reason or `refused`. */\n readonly refused: readonly { url: string; reason: string }[];\n /** True when at least one server accepted it (D-028). */\n readonly ok: boolean;\n}\n\n/** One server's answer, as applesauce-relay's `PublishResponse` carries it. */\nexport interface PublishAnswer {\n readonly ok: boolean;\n readonly from: string;\n readonly message?: string;\n}\n\n/**\n * The server URL in its normalised form, or as given when it is not a server URL.\n *\n * @param url - A server URL as written anywhere.\n * @returns The normalised URL, or `url` unchanged.\n * @example\n * ```ts\n * relayKey('wss://Relay.Example'); // 'wss://relay.example/'\n * relayKey('not a server'); // 'not a server'\n * ```\n */\nexport function relayKey(url: string): string {\n return toRelayUrl(url) ?? url;\n}\n\n/**\n * A server URL in its normalised form, when it is one. Only `ws:` and `wss:`\n * count: applesauce's normaliser would turn `https://` or a bare word into a\n * server address, and NIP-66 lets a report name a server by pubkey.\n *\n * @param url - A server URL as written anywhere.\n * @returns The normalised URL, or undefined.\n * @example\n * ```ts\n * toRelayUrl('wss://Relay.Example'); // 'wss://relay.example/'\n * toRelayUrl('https://relay.example'); // undefined\n * ```\n */\nexport function toRelayUrl(url: string): string | undefined {\n if (!/^wss?:\\/\\//i.test(url.trim())) return undefined;\n try {\n return normalizeRelayUrl(url);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Normalise a list of server URLs, dropping duplicates and anything that is not a server URL.\n *\n * @param urls - Server URLs as written anywhere.\n * @returns The normalised URLs, first occurrence first.\n * @example\n * ```ts\n * relayUrls(['wss://a.example', 'wss://A.example/', 'https://b.example']); // ['wss://a.example/']\n * ```\n */\nexport function relayUrls(urls: Iterable<string>): string[] {\n const seen = new Set<string>();\n for (const url of urls) {\n const normalized = toRelayUrl(url);\n if (normalized) seen.add(normalized);\n }\n return [...seen];\n}\n\n/**\n * Fold the servers' answers to one publish into an outcome. A server that\n * answered more than once counts once, and an acceptance wins over a refusal,\n * because the event is on that server either way.\n *\n * @param responses - The answers `RelayPool.publish` resolved with.\n * @returns Who accepted, who refused and why, and whether anyone accepted.\n * @example\n * ```ts\n * const outcome = summarizePublish(await pool.publish(relays, event));\n * outcome.ok; // true when 2 of 3 accepted\n * ```\n */\nexport function summarizePublish(responses: readonly PublishAnswer[]): PublishOutcome {\n const accepted: string[] = [];\n const refused = new Map<string, string>();\n for (const response of responses) {\n const url = relayKey(response.from);\n if (accepted.includes(url)) continue;\n if (response.ok) {\n accepted.push(url);\n refused.delete(url);\n } else {\n refused.set(url, response.message || 'refused');\n }\n }\n return {\n accepted,\n refused: [...refused].map(([url, reason]) => ({ url, reason })),\n ok: accepted.length > 0,\n };\n}\n\n/**\n * Say what came of a publish in words for the person. The sentence never\n * repeats a server's reason, which is written for developers and often names\n * the protocol.\n *\n * @param outcome - The result of {@link summarizePublish}.\n * @returns A sentence such as `Saved to 2 of 3 servers` or `No server accepted it`.\n * @example\n * ```ts\n * describeOutcome({ accepted: ['wss://a/'], refused: [{ url: 'wss://b/', reason: 'blocked' }], ok: true });\n * // 'Saved to 1 of 2 servers'\n * ```\n */\nexport function describeOutcome(outcome: PublishOutcome): string {\n const total = outcome.accepted.length + outcome.refused.length;\n if (total === 0) return 'There was no server to save it to';\n if (!outcome.ok) return 'No server accepted it';\n if (outcome.refused.length > 0) return `Saved to ${outcome.accepted.length} of ${total} servers`;\n return total === 1 ? 'Saved to 1 server' : `Saved to all ${total} servers`;\n}\n","import { auditTime, BehaviorSubject, isObservable, map, Subject, type Observable, type Subscription } from 'rxjs';\nimport type { RelayPool } from 'applesauce-relay';\nimport type { NostrEvent } from 'applesauce-core/helpers';\nimport {\n RELAY_DISCOVERY_KIND,\n getRelayDiscoveryAcceptedKinds,\n getRelayDiscoveryNetworkType,\n getRelayDiscoveryRequirements,\n getRelayDiscoveryRTT,\n getRelayDiscoverySupportedNIPs,\n getRelayDiscoveryTypes,\n getRelayDiscoveryURL,\n} from 'applesauce-common/helpers';\nimport { relayUrls, toRelayUrl } from './publish-outcome.js';\n\n/**\n * Servers that carry NIP-66 monitors' reports: the ones nostr.watch's own\n * client reads. Its history server is left out: its certificate does not\n * match its name, so a browser refuses it.\n *\n * @example\n * ```ts\n * createRelayDirectory({ pool, relays: DEFAULT_MONITOR_RELAYS });\n * ```\n */\nexport const DEFAULT_MONITOR_RELAYS: readonly string[] = Object.freeze([\n 'wss://relay.nostr.watch',\n 'wss://relaypag.es',\n 'wss://monitorlizard.nostr1.com',\n]);\n\n/** What a suggestion is for: where the account is reached, where it writes, or where accounts' lists are looked up. */\nexport type SuggestPurpose = 'inbox' | 'outbox' | 'lookup';\n\n/**\n * What the directory suggests when it knows nothing, per purpose. General\n * servers for inbox and outbox; servers that index profiles and server lists\n * for lookup.\n *\n * @example\n * ```ts\n * DEFAULT_SUGGESTIONS.lookup; // ['wss://purplepag.es', 'wss://user.kindpag.es', 'wss://indexer.coracle.social']\n * ```\n */\nexport const DEFAULT_SUGGESTIONS: Readonly<Record<SuggestPurpose, readonly string[]>> = Object.freeze({\n inbox: Object.freeze(['wss://relay.damus.io', 'wss://nos.lol', 'wss://relay.primal.net']),\n outbox: Object.freeze(['wss://relay.damus.io', 'wss://nos.lol', 'wss://relay.primal.net']),\n lookup: Object.freeze(['wss://purplepag.es', 'wss://user.kindpag.es', 'wss://indexer.coracle.social']),\n});\n\n/** One server as the monitors that watch it describe it. */\nexport interface RelayListing {\n /** The normalised server URL. */\n readonly url: string;\n /** How many distinct monitors reported on it within the directory's window. */\n readonly monitors: number;\n /** The newest report's `created_at`, in seconds. */\n readonly lastSeen: number;\n /** Mean connection time in milliseconds across the monitors that measured it. */\n readonly rttOpen?: number;\n /** Mean read time in milliseconds. */\n readonly rttRead?: number;\n /** Mean write time in milliseconds. */\n readonly rttWrite?: number;\n /** The newest report's network, such as `clearnet`. */\n readonly network?: string;\n /** Every NIP any monitor saw it support, ascending. */\n readonly nips: readonly number[];\n /** Every server type any monitor gave it, such as `PublicOutbox`. */\n readonly types: readonly string[];\n /** The newest report says it requires a login. */\n readonly requiresAuth: boolean;\n /** The newest report says it requires payment. */\n readonly requiresPayment: boolean;\n /** The newest report says it accepts writes only from some accounts. */\n readonly restrictedWrites: boolean;\n}\n\n/** Options for {@link RelayDirectory.suggest}. */\nexport interface SuggestOptions {\n readonly purpose: SuggestPurpose;\n /** Servers already chosen, left out of the answer. */\n readonly exclude?: readonly string[];\n /** How many to suggest; 3 by default, the middle of NIP-65's 2–4. */\n readonly limit?: number;\n}\n\n/** A live directory of monitored servers. */\nexport interface RelayDirectory {\n /** Every listing, best first, replayed to new subscribers and re-emitted at most every `throttleMs` while reports stream in. */\n readonly listings$: Observable<readonly RelayListing[]>;\n /** The listings as of now, best first. */\n listings(): readonly RelayListing[];\n /** Listings whose address matches what the person typed, best first. */\n search(text: string, limit?: number): readonly RelayListing[];\n /** Servers to suggest for a purpose: the well-known fallback first, unless monitors say it refuses, then durable hosts from the directory. */\n suggest(options: SuggestOptions): readonly RelayListing[];\n /** Open the streaming subscription. Does nothing when already open. */\n start(): void;\n /** Close it, keeping what was learned. */\n stop(): void;\n}\n\n/** The pool surface the directory needs. */\nexport type DirectoryPool = Pick<RelayPool, 'subscription'>;\n\n/** Options for {@link createRelayDirectory}. */\nexport interface RelayDirectoryOptions {\n readonly pool: DirectoryPool;\n /** Servers to read reports from; {@link DEFAULT_MONITOR_RELAYS} by default. */\n readonly relays?: readonly string[] | Observable<readonly string[]>;\n /** How old a report may be, in seconds; two days by default. */\n readonly maxAgeSeconds?: number;\n /** The clock, in seconds. */\n readonly now?: () => number;\n /** What to suggest when the directory knows too few: one list for every purpose, or one per purpose. {@link DEFAULT_SUGGESTIONS} by default. */\n readonly fallback?: readonly string[] | Partial<Readonly<Record<SuggestPurpose, readonly string[]>>>;\n /** The least time between two emissions of `listings$`, in milliseconds; 250 by default. */\n readonly throttleMs?: number;\n}\n\ninterface Built {\n readonly listings: readonly RelayListing[];\n readonly indexers: ReadonlySet<string>;\n}\n\nconst TWO_DAYS = 2 * 24 * 60 * 60;\nconst HOUR = 3600;\nconst DEFAULT_LIMIT = 3;\nconst INDEX_KINDS = new Set(['0', '10002']);\n\nfunction mean(values: readonly (number | undefined)[]): number | undefined {\n const known = values.filter((value): value is number => value !== undefined && Number.isFinite(value));\n return known.length === 0 ? undefined : known.reduce((sum, value) => sum + value, 0) / known.length;\n}\n\nfunction openTime(listing: RelayListing): number {\n return listing.rttOpen ?? Infinity;\n}\n\nfunction byRtt(a: RelayListing, b: RelayListing): number {\n return openTime(a) - openTime(b);\n}\n\n/** Seen by more monitors first, then seen within a more recent hour, then quicker to connect. */\nfunction rank(a: RelayListing, b: RelayListing): number {\n return b.monitors - a.monitors || Math.floor(b.lastSeen / HOUR) - Math.floor(a.lastSeen / HOUR) || byRtt(a, b) || a.url.localeCompare(b.url);\n}\n\nfunction listingFrom(url: string, reports: readonly NostrEvent[]): RelayListing {\n const newest = reports.reduce((best, event) => (event.created_at > best.created_at ? event : best));\n const requirements = getRelayDiscoveryRequirements(newest);\n const nips = new Set(reports.flatMap(getRelayDiscoverySupportedNIPs).map(Number).filter(Number.isInteger));\n const measured = {\n rttOpen: mean(reports.map((event) => getRelayDiscoveryRTT(event, 'open'))),\n rttRead: mean(reports.map((event) => getRelayDiscoveryRTT(event, 'read'))),\n rttWrite: mean(reports.map((event) => getRelayDiscoveryRTT(event, 'write'))),\n network: getRelayDiscoveryNetworkType(newest),\n };\n const known = Object.fromEntries(Object.entries(measured).filter(([, value]) => value !== undefined)) as Pick<RelayListing, keyof typeof measured>;\n return {\n url,\n monitors: reports.length,\n lastSeen: newest.created_at,\n ...known,\n nips: [...nips].sort((a, b) => a - b),\n types: [...new Set(reports.flatMap(getRelayDiscoveryTypes))],\n requiresAuth: requirements.includes('auth'),\n requiresPayment: requirements.includes('payment'),\n restrictedWrites: requirements.includes('writes'),\n };\n}\n\nfunction isIndexer(listing: RelayListing, reports: readonly NostrEvent[]): boolean {\n if (listing.nips.includes(65)) return true;\n if (listing.types.some((type) => type.toLowerCase().includes('indexer'))) return true;\n return reports.some((event) => getRelayDiscoveryAcceptedKinds(event).some((kind) => INDEX_KINDS.has(kind)));\n}\n\nfunction blocks(listing: RelayListing | undefined, purpose: SuggestPurpose): boolean {\n if (!listing) return false;\n if (listing.requiresAuth || listing.requiresPayment) return true;\n return purpose !== 'lookup' && listing.restrictedWrites;\n}\n\n/** Hosts that come and go: tunnels, private networks and test domains. A server there makes a poor home for an inbox. */\nconst PASSING_HOSTS = /(?:^|\\.)(?:trycloudflare\\.com|ngrok(?:-free)?\\.(?:app|io|dev)|loca\\.lt|ts\\.net|local|localhost|onion)$/i;\n\n/**\n * Whether a server is one to suggest: a named host on the default port at the\n * root, not a tunnel, a bare address or one path of a multi-purpose server.\n * Typed addresses are never held to this; it only shapes suggestions.\n */\nfunction isDurable(url: string): boolean {\n const { hostname, port, pathname } = new URL(url);\n return port === '' && pathname === '/' && !PASSING_HOSTS.test(hostname) && !/^[\\d.]+$|:/.test(hostname);\n}\n\nfunction placeholder(url: string): RelayListing {\n return { url, monitors: 0, lastSeen: 0, nips: [], types: [], requiresAuth: false, requiresPayment: false, restrictedWrites: false };\n}\n\nfunction fallbackFor(fallback: RelayDirectoryOptions['fallback'], purpose: SuggestPurpose): string[] {\n if (Array.isArray(fallback)) return relayUrls(fallback);\n const lists = (fallback ?? {}) as Partial<Record<SuggestPurpose, readonly string[]>>;\n return relayUrls(lists[purpose] ?? DEFAULT_SUGGESTIONS[purpose]);\n}\n\ninterface Query {\n readonly text: string;\n /** The person typed a scheme, so they are typing the address from its start. */\n readonly anchored: boolean;\n}\n\nfunction parseQuery(raw: string): Query {\n const lower = raw.trim().toLowerCase();\n const text = lower.replace(/^wss?:\\/\\//, '').replace(/\\/+$/, '');\n return { text, anchored: text !== lower.replace(/\\/+$/, '') };\n}\n\n/** 3 when the text starts the name a person knows the server by, 2 when it starts the address or one of its words, 1 when it appears inside, 0 otherwise. */\nfunction matchScore(url: string, query: Query): number {\n const address = url.replace(/^wss?:\\/\\//, '').replace(/\\/$/, '');\n if (!query.anchored && address.replace(/^(?:relay|nostr)\\./, '').startsWith(query.text)) return 3;\n if (address.startsWith(query.text)) return 2;\n if (query.anchored) return 0;\n if (address.split(/[.\\-/]/).some((word) => word.startsWith(query.text))) return 2;\n return address.includes(query.text) ? 1 : 0;\n}\n\n/**\n * Create a directory of servers from NIP-66 monitors' reports (kind 30166).\n *\n * `start()` streams reports newer than `maxAgeSeconds` for the `clearnet`\n * network from the monitor servers; a browser cannot dial the other networks,\n * and NIP-66 says a report SHOULD carry its network, so the filter asks the\n * servers to leave the rest out. A server that ignores the filter is\n * re-checked here: a report naming another network is dropped, one naming none\n * is kept. Each monitor's newest report per server counts; listings fold them\n * across monitors. NIP-66 warns that a monitor may be wrong or hostile, so the\n * directory only ranks, completes and suggests: it never removes a server the\n * person chose, and with no report at all `suggest` answers from the fallback\n * (D-029).\n *\n * @param options - The pool, the monitor servers, the window, the clock and the fallback.\n * @returns A directory; call `start()` to begin streaming.\n * @example\n * ```ts\n * const directory = createRelayDirectory({ pool });\n * directory.start();\n * directory.search('damus');\n * directory.suggest({ purpose: 'inbox', exclude: current });\n * ```\n */\nexport function createRelayDirectory(options: RelayDirectoryOptions): RelayDirectory {\n const now = options.now ?? (() => Math.floor(Date.now() / 1000));\n const maxAge = options.maxAgeSeconds ?? TWO_DAYS;\n const reports = new Map<string, Map<string, NostrEvent>>();\n const changed = new Subject<void>();\n let built: (Built & { readonly cutoff: number }) | undefined;\n let subscription: Subscription | undefined;\n\n function build(cutoff: number): Built & { readonly cutoff: number } {\n const listings: RelayListing[] = [];\n const indexers = new Set<string>();\n for (const [url, byMonitor] of reports) {\n const fresh = [...byMonitor.values()].filter((event) => event.created_at >= cutoff);\n if (fresh.length === 0) continue;\n const listing = listingFrom(url, fresh);\n listings.push(listing);\n if (isIndexer(listing, fresh)) indexers.add(url);\n }\n return { listings: listings.sort(rank), indexers, cutoff };\n }\n\n const current = (): Built => {\n const cutoff = now() - maxAge;\n if (built?.cutoff !== cutoff) built = build(cutoff);\n return built;\n };\n const listings$ = new BehaviorSubject<readonly RelayListing[]>([]);\n changed.pipe(auditTime(options.throttleMs ?? 250)).subscribe(() => listings$.next(current().listings));\n\n function ingest(event: NostrEvent): void {\n if (event.kind !== RELAY_DISCOVERY_KIND || event.created_at < now() - maxAge) return;\n const network = getRelayDiscoveryNetworkType(event);\n const url = toRelayUrl(getRelayDiscoveryURL(event) ?? '');\n if ((network !== undefined && network !== 'clearnet') || url === undefined) return;\n const byMonitor = reports.get(url) ?? new Map<string, NostrEvent>();\n const previous = byMonitor.get(event.pubkey);\n if (previous && previous.created_at >= event.created_at) return;\n byMonitor.set(event.pubkey, event);\n reports.set(url, byMonitor);\n built = undefined;\n changed.next();\n }\n\n function monitorRelays(): string[] | Observable<string[]> {\n const relays = options.relays ?? DEFAULT_MONITOR_RELAYS;\n return isObservable(relays) ? relays.pipe(map((list) => [...list])) : [...relays];\n }\n\n function suggest({ purpose, exclude = [], limit = DEFAULT_LIMIT }: SuggestOptions): readonly RelayListing[] {\n const { listings, indexers } = current();\n const skip = new Set(relayUrls(exclude));\n const known = new Map(listings.map((listing) => [listing.url, listing]));\n // Well-known servers come first unless a monitor says they now refuse; the directory fills the rest with durable hosts.\n const trusted = fallbackFor(options.fallback, purpose)\n .filter((url) => !skip.has(url) && !blocks(known.get(url), purpose))\n .map((url) => known.get(url) ?? placeholder(url));\n const taken = new Set(trusted.map((listing) => listing.url));\n const found = listings.filter(\n (listing) => !skip.has(listing.url) && !taken.has(listing.url) && !blocks(listing, purpose) && isDurable(listing.url) && (purpose !== 'lookup' || indexers.has(listing.url)),\n );\n return [...trusted, ...found].slice(0, limit);\n }\n\n return {\n listings$: listings$.asObservable(),\n listings: () => current().listings,\n search(text, limit = 10) {\n const query = parseQuery(text);\n return current()\n .listings.map((listing) => ({ listing, score: matchScore(listing.url, query) }))\n .filter((entry) => entry.score > 0)\n .sort((a, b) => b.score - a.score || b.listing.monitors - a.listing.monitors || byRtt(a.listing, b.listing))\n .slice(0, limit)\n .map((entry) => entry.listing);\n },\n suggest,\n start() {\n if (subscription && !subscription.closed) return;\n const filter = { kinds: [RELAY_DISCOVERY_KIND], '#n': ['clearnet'], since: now() - maxAge };\n subscription = options.pool.subscription(monitorRelays(), [filter]).subscribe({\n next: ingest,\n error: () => undefined,\n });\n },\n stop() {\n subscription?.unsubscribe();\n subscription = undefined;\n },\n };\n}\n","import { BehaviorSubject, combineLatest, distinctUntilChanged, map, of, Observable, switchMap, timer, type Subscription } from 'rxjs';\nimport type { EventStore } from 'applesauce-core';\nimport type { RelayPool } from 'applesauce-relay';\nimport type { ISigner } from 'applesauce-signers';\nimport { unixNow, type NostrEvent } from 'applesauce-core/helpers';\nimport { subscribeWithEose } from '../applesauce/relay-hooks.js';\nimport { DEFAULT_SUGGESTIONS, type RelayDirectory } from './directory.js';\nimport { relayUrls, summarizePublish, toRelayUrl, type PublishAnswer, type PublishOutcome } from './publish-outcome.js';\n\n/** The NIP-65 relay list kind. */\nconst RELAY_LIST_KIND = 10002;\n/** The extreme cap on waiting for a lookup server that never finishes. */\nconst PATIENCE_MS = 15_000;\nconst SUGGESTED = 3;\n\n/** Where an account is reached (inboxes, NIP-65 `read`) and where it writes (outboxes, `write`). */\nexport interface Mailboxes {\n readonly inboxes: readonly string[];\n readonly outboxes: readonly string[];\n}\n\n/** The account's published list, as the shell knows it now. */\nexport type MailboxState =\n | { readonly status: 'loading' }\n | { readonly status: 'missing'; readonly suggested: Mailboxes }\n | { readonly status: 'found'; readonly mailboxes: Mailboxes; readonly event: NostrEvent };\n\n/** The active account's inbox and outbox. */\nexport interface AccountMailboxes {\n /** The state, replayed to new subscribers. */\n readonly state$: Observable<MailboxState>;\n /** The state as of now. */\n state(): MailboxState;\n /**\n * Publish a new list. Resolves with who accepted it; rejects with `denied:read-only` or `invalid:relay-url`.\n * `onProgress` hears the outcome so far each time a server answers, when the pool can report answers one by one.\n */\n save(next: Mailboxes, onProgress?: (sofar: PublishOutcome) => void): Promise<PublishOutcome>;\n}\n\n/** The signer surface saving needs. */\nexport type MailboxSigner = Pick<ISigner, 'getPublicKey' | 'signEvent'>;\n\n/** The pool surface the mailboxes need. */\nexport type MailboxPool = Pick<RelayPool, 'req' | 'publish'> & Partial<Pick<RelayPool, 'event'>>;\n\n/** Options for {@link createAccountMailboxes}. */\nexport interface AccountMailboxesOptions {\n /** The shell's event store; found and saved lists are added to it. */\n readonly store: EventStore;\n readonly pool: MailboxPool;\n /** The active account's public key; the lookup follows it and ends when it completes. */\n readonly pubkey$: Observable<string | undefined>;\n /** Servers that index accounts' lists, asked on every lookup and every save. */\n readonly lookupRelays: () => readonly string[];\n /** The active account's signer, when it can sign. */\n readonly signer: () => MailboxSigner | undefined;\n /** Suggestions for an account with no list; the built-in ones without it. */\n readonly directory?: RelayDirectory;\n /** How long to wait for a lookup server that never finishes; 15 s by default. */\n readonly patienceMs?: number;\n}\n\n/**\n * Read a NIP-65 list. An unmarked `r` tag is both an inbox and an outbox; a\n * tag with any other marker, or a value that is not a `ws:` or `wss:` URL, is\n * skipped. applesauce's `getInboxes` is not used because its URL check refuses\n * top-level domains longer than six letters.\n *\n * @param event - A kind 10002 event, or nothing.\n * @returns Normalised inboxes and outboxes; empty for no event.\n * @example\n * ```ts\n * mailboxesFromEvent({ ...event, tags: [['r', 'wss://a.example'], ['r', 'wss://b.example', 'read']] });\n * // { inboxes: ['wss://a.example/', 'wss://b.example/'], outboxes: ['wss://a.example/'] }\n * ```\n */\nexport function mailboxesFromEvent(event: NostrEvent | undefined): Mailboxes {\n const inboxes = new Set<string>();\n const outboxes = new Set<string>();\n for (const [name, value = '', marker] of event?.tags ?? []) {\n const url = toRelayUrl(value);\n if (name !== 'r' || !url || (marker !== undefined && marker !== 'read' && marker !== 'write')) continue;\n if (marker !== 'write') inboxes.add(url);\n if (marker !== 'read') outboxes.add(url);\n }\n return { inboxes: [...inboxes], outboxes: [...outboxes] };\n}\n\nfunction strictUrls(urls: readonly string[]): string[] {\n return relayUrls(\n urls.map((url) => {\n if (!toRelayUrl(url)) throw new Error('invalid:relay-url');\n return url;\n }),\n );\n}\n\n/**\n * The tags of the next NIP-65 list: one `r` tag per server, unmarked when it\n * is both an inbox and an outbox, then every tag of the previous list that is\n * not an `r` tag, so what other clients wrote is kept.\n *\n * @param mailboxes - The inboxes and outboxes to publish.\n * @param previous - The list being replaced, if any.\n * @returns The tags. Throws `invalid:relay-url` for an entry that is not a `ws:` or `wss:` URL.\n * @example\n * ```ts\n * mailboxTags({ inboxes: ['wss://a.example', 'wss://b.example'], outboxes: ['wss://a.example'] });\n * // [['r', 'wss://a.example/'], ['r', 'wss://b.example/', 'read']]\n * ```\n */\nexport function mailboxTags(mailboxes: Mailboxes, previous?: NostrEvent): string[][] {\n const inboxes = strictUrls(mailboxes.inboxes);\n const outboxes = strictUrls(mailboxes.outboxes);\n const tags = relayUrls([...inboxes, ...outboxes]).map((url) => {\n if (!outboxes.includes(url)) return ['r', url, 'read'];\n if (!inboxes.includes(url)) return ['r', url, 'write'];\n return ['r', url];\n });\n const kept = (previous?.tags ?? []).filter((tag) => tag[0] !== 'r').map((tag) => [...tag]);\n return [...tags, ...kept];\n}\n\nfunction suggestions(directory: RelayDirectory | undefined): Mailboxes {\n if (!directory) {\n const general = relayUrls(DEFAULT_SUGGESTIONS.inbox).slice(0, SUGGESTED);\n return { inboxes: general, outboxes: relayUrls(DEFAULT_SUGGESTIONS.outbox).slice(0, SUGGESTED) };\n }\n const urls = (purpose: 'inbox' | 'outbox'): string[] => directory.suggest({ purpose, limit: SUGGESTED }).map((listing) => listing.url);\n return { inboxes: urls('inbox'), outboxes: urls('outbox') };\n}\n\nfunction sameState(a: MailboxState, b: MailboxState): boolean {\n if (a.status === 'found' && b.status === 'found') return a.event.id === b.event.id;\n if (a.status === 'missing' && b.status === 'missing') return JSON.stringify(a.suggested) === JSON.stringify(b.suggested);\n return a.status === b.status;\n}\n\n/** Becomes true once every lookup server has finished, or once the cap passes. */\nfunction lookupFinished(options: AccountMailboxesOptions, pubkey: string): Observable<boolean> {\n return new Observable<boolean>((observer) => {\n observer.next(false);\n const finish = (): void => observer.next(true);\n const cap: Subscription = timer(options.patienceMs ?? PATIENCE_MS).subscribe(finish);\n const lookup = subscribeWithEose(options.pool, relayUrls(options.lookupRelays()), [{ kinds: [RELAY_LIST_KIND], authors: [pubkey] }], (item) => {\n if (item === 'EOSE') finish();\n else options.store.add(item as NostrEvent);\n });\n return () => {\n cap.unsubscribe();\n lookup.unsubscribe();\n };\n }).pipe(distinctUntilChanged());\n}\n\nfunction stateFor(options: AccountMailboxesOptions, pubkey: string | undefined): Observable<MailboxState> {\n if (pubkey === undefined) return of({ status: 'loading' });\n const listings$ = options.directory?.listings$ ?? of([]);\n return combineLatest([options.store.replaceable(RELAY_LIST_KIND, pubkey), lookupFinished(options, pubkey), listings$]).pipe(\n map(([event, finished]): MailboxState => {\n if (event) return { status: 'found', mailboxes: mailboxesFromEvent(event), event };\n if (!finished) return { status: 'loading' };\n return { status: 'missing', suggested: suggestions(options.directory) };\n }),\n );\n}\n\n/** Publish through the pool's per-server stream, reporting each answer; a server that never answers counts as refusing. */\nfunction publishStreaming(publish: NonNullable<MailboxPool['event']>, relays: string[], event: NostrEvent, onProgress: (sofar: PublishOutcome) => void): Promise<PublishOutcome> {\n const answers: PublishAnswer[] = [];\n return new Promise((resolve) => {\n const finish = (): void => {\n const silent = relays.filter((url) => !answers.some((answer) => answer.from === url));\n resolve(summarizePublish([...answers, ...silent.map((from) => ({ ok: false, from, message: 'no answer' }))]));\n };\n publish(relays, event).subscribe({\n next(answer) {\n answers.push(answer);\n onProgress(summarizePublish(answers));\n },\n error: finish,\n complete: finish,\n });\n });\n}\n\nasync function publishList(options: AccountMailboxesOptions, signer: MailboxSigner, next: Mailboxes, onProgress?: (sofar: PublishOutcome) => void): Promise<PublishOutcome> {\n const pubkey = await signer.getPublicKey();\n const previous = options.store.getReplaceable(RELAY_LIST_KIND, pubkey);\n const tags = mailboxTags(next, previous);\n const created_at = Math.max(unixNow(), (previous?.created_at ?? 0) + 1);\n const event = await signer.signEvent({ kind: RELAY_LIST_KIND, created_at, tags, content: previous?.content ?? '' });\n const old = mailboxesFromEvent(previous);\n // NIP-65: the list goes to where the account writes and is read, old and new, and to the indexers.\n const relays = relayUrls([...next.outboxes, ...old.outboxes, ...next.inboxes, ...options.lookupRelays()]);\n const stream = options.pool.event?.bind(options.pool);\n if (stream && onProgress) {\n // The list is shown as soon as one server holds it; the rest keep answering.\n const progress = (sofar: PublishOutcome): void => {\n if (sofar.ok) options.store.add(event);\n onProgress(sofar);\n };\n return publishStreaming(stream, relays, event, progress);\n }\n const outcome = await options.pool.publish(relays, event).then(summarizePublish, (error: unknown) => ({\n accepted: [],\n refused: relays.map((url) => ({ url, reason: String(error).replace(/^Error: /, '') })),\n ok: false,\n }));\n if (outcome.ok) options.store.add(event);\n return outcome;\n}\n\n/**\n * Watch the active account's NIP-65 list and save a new one.\n *\n * The list is streamed from `lookupRelays()` for whichever account `pubkey$`\n * names, added to the store, and kept open so a newer list from another\n * client replaces it; the store keeps the newest. The state is `loading`\n * until a list arrives or every server has finished, or failed, without one,\n * or `patienceMs` passes for a server that never answers; it is then\n * `missing` with suggestions from the directory. With nobody signed in it\n * stays `loading`. Saving signs the list with the active signer, publishes it\n * to the new outboxes, the old outboxes, the new inboxes and the lookup\n * servers, and succeeds when any of them accepts it (D-028). A list nobody\n * accepted is not added to the store, so the state never shows a list no\n * server holds.\n *\n * @param options - The store, pool, active account, lookup servers, signer and directory.\n * @returns The account's mailboxes.\n * @example\n * ```ts\n * const mailboxes = createAccountMailboxes({ store, pool, pubkey$, lookupRelays: () => tiers.get().discovery, signer });\n * mailboxes.state$.subscribe((state) => render(state));\n * const outcome = await mailboxes.save({ inboxes: ['wss://in.example'], outboxes: ['wss://out.example'] });\n * describeOutcome(outcome); // 'Saved to 3 of 4 servers'\n * ```\n */\nexport function createAccountMailboxes(options: AccountMailboxesOptions): AccountMailboxes {\n const state$ = new BehaviorSubject<MailboxState>({ status: 'loading' });\n options.pubkey$\n .pipe(switchMap((pubkey) => stateFor(options, pubkey)))\n .subscribe((state) => {\n if (!sameState(state$.value, state)) state$.next(state);\n });\n return {\n state$: state$.asObservable(),\n state: () => state$.value,\n async save(next, onProgress) {\n const signer = options.signer();\n if (!signer) throw new Error('denied:read-only');\n return publishList(options, signer, next, onProgress);\n },\n };\n}\n","import type { RelayPool } from 'applesauce-relay';\nimport { normalizeRelayUrl, type Filter } from 'applesauce-core/helpers';\nimport type { NappletMessageTarget, RelayPoolHooks, RelayPoolLike } from '@kehto/shell';\nimport type { NostrEvent, NostrFilter } from '@napplet/core';\nimport { NAPPLET_KINDS } from '@kehto/nip/5d';\nimport type { RelayTiers } from '../types.js';\n\n/** The slice of applesauce's `RelayPool` kernl adapts. Narrow so tests can supply a fake. */\nexport type ApplesaucePool = Pick<RelayPool, 'req' | 'request' | 'publish'>;\n\n/** Replaceable kinds that live on the discovery tier. */\nconst DISCOVERY_KINDS: ReadonlySet<number> = new Set([0, 3, 10002]);\n/** Applet manifests and the legacy catalogue kind. */\nconst APP_KINDS: ReadonlySet<number> = new Set([...NAPPLET_KINDS, 32267]);\n\n/** A subscription that delivers events once each and signals the end of stored events. */\nexport interface EoseSubscription {\n unsubscribe(): void;\n}\n\n/**\n * View NAP filters as applesauce filters. The two types describe the same\n * NIP-01 object; applesauce adds an index signature for NIP-91 `&` tags that\n * the NAP type does not declare.\n *\n * @param filters - NAP filters.\n * @returns The same array typed for applesauce.\n * @example\n * ```ts\n * pool.request(relays, asFilters(filters));\n * ```\n */\nexport function asFilters(filters: NostrFilter[]): Filter[] {\n return filters as Filter[];\n}\n\n/**\n * Subscribe through the pool's raw `req` so the end of stored events is\n * observable: `EOSE` is reported once, after every relay has answered or\n * failed, and events are deduplicated by id because `req` does not.\n * applesauce's `subscription()` deduplicates but hides `EOSE`, which kehto's\n * relay service relies on to answer `relay.subscribe`.\n *\n * @param pool - The shared applesauce pool.\n * @param relays - Relay URLs to ask.\n * @param filters - Filters for the request.\n * @param callback - Receives each new event once, then `'EOSE'`.\n * @returns A handle that closes the subscription.\n * @example\n * ```ts\n * const sub = subscribeWithEose(pool, ['wss://relay.example'], [{ kinds: [1] }], (item) => {\n * if (item !== 'EOSE') console.log(item.id);\n * });\n * sub.unsubscribe();\n * ```\n */\nexport function subscribeWithEose(\n pool: Pick<ApplesaucePool, 'req'>,\n relays: string[],\n filters: NostrFilter[],\n callback: (item: NostrEvent | 'EOSE') => void,\n): EoseSubscription {\n const seen = new Set<string>();\n const waiting = new Set(relays.map(normalizeRelayUrl));\n let eoseSent = waiting.size === 0;\n if (eoseSent) callback('EOSE');\n const settle = (from: string): void => {\n waiting.delete(normalizeRelayUrl(from));\n if (eoseSent || waiting.size > 0) return;\n eoseSent = true;\n callback('EOSE');\n };\n const subscription = pool.req(relays, asFilters(filters)).subscribe((message) => {\n if (message.type === 'EVENT') {\n if (seen.has(message.event.id)) return;\n seen.add(message.event.id);\n callback(message.event as NostrEvent);\n return;\n }\n if (message.type !== 'OPEN') settle(message.from);\n });\n return { unsubscribe: () => subscription.unsubscribe() };\n}\n\n/**\n * Adapt the shared applesauce `RelayPool` to kehto's `RelayPoolLike`.\n *\n * @param pool - The one pool the shell owns (D-002).\n * @returns An object kehto's `RelayPoolHooks.getRelayPool` can return.\n * @example\n * ```ts\n * const like = createRelayPoolLike(pool);\n * like.subscription(['wss://relay.example'], [{ kinds: [1] }]).subscribe((item) => {});\n * ```\n */\nexport function createRelayPoolLike(pool: ApplesaucePool): RelayPoolLike {\n return {\n subscription(relayUrls, filters) {\n return {\n subscribe(observer) {\n return subscribeWithEose(pool, relayUrls, filters as NostrFilter[], observer);\n },\n };\n },\n request(relayUrls, filters) {\n return {\n subscribe(observer) {\n const subscription = pool.request(relayUrls, asFilters(filters as NostrFilter[])).subscribe({\n next: (event) => observer.next(event),\n complete: () => observer.complete(),\n error: () => observer.error(),\n });\n return { unsubscribe: () => subscription.unsubscribe() };\n },\n };\n },\n async publish(relayUrls, event) {\n await pool.publish(relayUrls, event as NostrEvent);\n },\n };\n}\n\nfunction kindsOf(filters: readonly NostrFilter[]): number[] | undefined {\n const kinds: number[] = [];\n for (const filter of filters) {\n if (!filter.kinds || filter.kinds.length === 0) return undefined;\n kinds.push(...filter.kinds);\n }\n return kinds;\n}\n\nfunction unique(urls: readonly string[]): string[] {\n return [...new Set(urls)];\n}\n\n/**\n * Choose the relay tier for a set of filters.\n *\n * Profiles, follow lists and relay lists come from the discovery tier; applet\n * manifests from the apps tier; everything else goes to the user's outbox\n * relays plus the super tier. A filter without kinds cannot be classified and\n * takes the general path.\n *\n * @param tiers - The current tier configuration.\n * @param filters - Filters about to be sent.\n * @returns Relay URLs, deduplicated.\n * @example\n * ```ts\n * selectRelayTier(tiers, [{ kinds: [0], authors: [pubkey] }]); // discovery, then outbox and super\n * ```\n */\nexport function selectRelayTier(tiers: RelayTiers, filters: readonly NostrFilter[]): string[] {\n const config = tiers.get();\n const kinds = kindsOf(filters);\n if (kinds && kinds.length > 0) {\n // Profiles, follows and relay lists live on indexers and on their authors' own servers (NIP-65), so both are asked.\n if (kinds.every((kind) => DISCOVERY_KINDS.has(kind))) return unique([...config.discovery, ...config.outbox, ...config.super]);\n if (kinds.every((kind) => APP_KINDS.has(kind))) return unique(config.apps);\n }\n return unique([...config.super, ...config.outbox]);\n}\n\n/**\n * Build kehto's `RelayPoolHooks` over the shared applesauce pool.\n *\n * Scoped relays (one relay per window, the NIP-29 pattern) are kept minimal:\n * one open subscription per window, replaced on reopen, and events delivered\n * to the window's bound port as `relay.event` envelopes.\n *\n * @param pool - The shared applesauce pool.\n * @param tiers - Relay tiers used for `selectRelayTier`.\n * @returns Hooks for `ShellAdapter.relayPool`.\n * @example\n * ```ts\n * const adapter: ShellAdapter = { relayPool: createRelayPoolHooks(pool, tiers), ... };\n * ```\n */\nexport function createRelayPoolHooks(pool: ApplesaucePool, tiers: RelayTiers): RelayPoolHooks {\n const like = createRelayPoolLike(pool);\n const tracked = new Map<string, () => void>();\n const scoped = new Map<string, { relayUrl: string; subscription: EoseSubscription }>();\n\n const closeScopedRelay = (windowId: string): void => {\n scoped.get(windowId)?.subscription.unsubscribe();\n scoped.delete(windowId);\n };\n\n return {\n getRelayPool: () => like,\n trackSubscription(subKey, cleanup) {\n tracked.get(subKey)?.();\n tracked.set(subKey, cleanup);\n },\n untrackSubscription(subKey) {\n tracked.get(subKey)?.();\n tracked.delete(subKey);\n },\n openScopedRelay(windowId: string, relayUrl: string, subId: string, filters: NostrFilter[], target: NappletMessageTarget) {\n closeScopedRelay(windowId);\n const subscription = subscribeWithEose(pool, [relayUrl], filters, (item) => {\n target.postMessage(item === 'EOSE' ? { type: 'relay.eose', subId } : { type: 'relay.event', subId, event: item });\n });\n scoped.set(windowId, { relayUrl, subscription });\n },\n closeScopedRelay,\n async publishToScopedRelay(windowId, event) {\n const entry = scoped.get(windowId);\n if (!entry) return false;\n try {\n const [response] = await pool.publish([entry.relayUrl], event);\n return response?.ok === true;\n } catch {\n return false;\n }\n },\n selectRelayTier: (filters) => selectRelayTier(tiers, filters),\n };\n}\n","import { lastValueFrom, toArray } from 'rxjs';\nimport type { DmRelayPool, RelayPoolServiceOptions } from '@kehto/services';\nimport type { NostrEvent, NostrFilter } from '@napplet/core';\nimport type { RelayTiers } from '../types.js';\nimport { asFilters, selectRelayTier, subscribeWithEose, type ApplesaucePool } from './relay-hooks.js';\n\n/** The relay-pool shape kehto's outbox router consumes. Declared structurally so core needs no extra import. */\nexport interface OutboxRelayPoolLike {\n subscribe(filters: NostrFilter[], relayUrls: string[], callback: (item: NostrEvent | 'EOSE') => void): { unsubscribe(): void };\n publish(event: NostrEvent, relayUrls: string[]): Promise<Record<string, boolean>>;\n isAvailable(): boolean;\n}\n\n/**\n * Publish to every relay and succeed when any one accepts. A relay that refuses\n * or is unreachable is normal on an open network; only when none accepted is\n * the publish a failure, and then the reason names how many were tried (D-028).\n *\n * @param pool - The shared applesauce pool.\n * @param relays - Where to publish.\n * @param event - The signed event.\n * @returns How many relays accepted it.\n * @example\n * ```ts\n * await publishAccepted(pool, ['wss://a', 'wss://b'], event); // 1 when only one accepted\n * ```\n */\nexport async function publishAccepted(pool: ApplesaucePool, relays: string[], event: NostrEvent): Promise<number> {\n const responses = relays.length > 0 ? await pool.publish(relays, event) : [];\n const accepted = responses.filter((response) => response.ok).length;\n if (accepted === 0) throw new Error(`unavailable:not-accepted:0/${relays.length}`);\n return accepted;\n}\n\nasync function publishTo(pool: ApplesaucePool, relays: string[], event: NostrEvent): Promise<Record<string, boolean>> {\n const responses = await pool.publish(relays, event);\n return Object.fromEntries(responses.map((response) => [response.from, response.ok]));\n}\n\n/**\n * Options for kehto's `createRelayPoolService` over the shared applesauce pool.\n *\n * Publishes go to the tier selected for the event's kind, so a profile update\n * lands on discovery relays and the user's own, and a note on the user's outbox\n * plus the super tier. A publish succeeds when any relay accepts it.\n *\n * @param pool - The shared applesauce pool.\n * @param tiers - Relay tiers used to route publishes and unhinted subscriptions.\n * @returns Options for `createRelayPoolService`.\n * @example\n * ```ts\n * runtime.registerService('relay', createRelayPoolService(createAppletRelayBackend(pool, tiers)));\n * ```\n */\nexport function createAppletRelayBackend(pool: ApplesaucePool, tiers: RelayTiers): RelayPoolServiceOptions {\n return {\n subscribe(filters, callback, relayUrls) {\n const relays = relayUrls ?? selectRelayTier(tiers, filters);\n return subscribeWithEose(pool, relays, filters, (item) => callback(item, relays));\n },\n async publish(event) {\n await publishAccepted(pool, selectRelayTier(tiers, [{ kinds: [event.kind] }]), event);\n },\n selectRelayTier: (filters) => selectRelayTier(tiers, filters),\n isAvailable: () => true,\n };\n}\n\n/**\n * The relay pool a messaging backend reads and writes through, satisfying\n * kehto's `DmRelayPool` over the same shared applesauce pool.\n *\n * @param pool - The shared applesauce pool.\n * @param tiers - Relay tiers used when a caller names no relays.\n * @returns A `DmRelayPool`.\n * @example\n * ```ts\n * const dmPool = createDmRelayPool(pool, tiers);\n * const history = await dmPool.query([{ kinds: [1059], '#p': [me] }]);\n * ```\n */\nexport function createDmRelayPool(pool: ApplesaucePool, tiers: RelayTiers): DmRelayPool {\n return {\n subscribe(filters, callback, relayUrls) {\n return subscribeWithEose(pool, relayUrls ?? selectRelayTier(tiers, filters), filters, callback);\n },\n async publish(event) {\n await publishAccepted(pool, selectRelayTier(tiers, [{ kinds: [event.kind] }]), event);\n },\n query(filters, relayUrls) {\n return lastValueFrom(pool.request(relayUrls ?? selectRelayTier(tiers, filters), asFilters(filters)).pipe(toArray()));\n },\n selectRelayTier: (filters) => selectRelayTier(tiers, filters),\n isAvailable: () => true,\n };\n}\n\n/**\n * The relay pool kehto's `createRelayPoolOutboxRouter` fans out through.\n *\n * @param pool - The shared applesauce pool.\n * @returns A pool with per-relay publish outcomes.\n * @example\n * ```ts\n * const router = createRelayPoolOutboxRouter({ relayPool: createOutboxRelayPool(pool), ... });\n * ```\n */\nexport function createOutboxRelayPool(pool: ApplesaucePool): OutboxRelayPoolLike {\n return {\n subscribe: (filters, relayUrls, callback) => subscribeWithEose(pool, relayUrls, filters, callback),\n publish: (event, relayUrls) => publishTo(pool, relayUrls, event),\n isAvailable: () => true,\n };\n}\n","import type { AccountManager, IAccount } from 'applesauce-accounts';\nimport type { AuthHooks } from '@kehto/shell';\nimport type { Signer } from '@kehto/runtime';\nimport type { SigningConsent } from '../consent/handler.js';\n\n/** Account types whose signer cannot sign. Mirrors `ReadonlyAccount.type` without importing the class. */\nconst READ_ONLY_TYPES: ReadonlySet<string> = new Set(['readonly']);\n\n/**\n * Whether an account can only show an identity, never sign for it.\n *\n * @param account - Any applesauce account.\n * @returns True for read-only accounts.\n * @example\n * ```ts\n * isReadOnlyAccount(ReadonlyAccount.fromPubkey(pubkey)); // true\n * ```\n */\nexport function isReadOnlyAccount(account: IAccount): boolean {\n return READ_ONLY_TYPES.has(account.type);\n}\n\n/**\n * Wrap an account as the NIP-07-shaped signer kehto expects.\n *\n * The account itself is never handed over: kehto sees four methods and the\n * encryption namespaces the account exposes, nothing that reveals key material.\n *\n * @param account - The active applesauce account.\n * @returns A kehto `Signer`.\n * @example\n * ```ts\n * const signer = wrapAccountSigner(account);\n * await signer.signEvent?.(template);\n * ```\n */\nexport function wrapAccountSigner(account: IAccount): Signer {\n const signer: Signer = {\n getPublicKey: () => account.getPublicKey(),\n signEvent: (template) => account.signEvent(template),\n };\n if (account.nip04) signer.nip04 = account.nip04;\n if (account.nip44) signer.nip44 = account.nip44;\n return signer;\n}\n\n/**\n * kehto `AuthHooks` over the applesauce `AccountManager`.\n *\n * `getSigner` returns null while nobody is signed in and for read-only accounts,\n * so the runtime refuses writes instead of failing inside a signer that throws.\n * When kehto names the requesting window, the signer it gets back puts every\n * `signEvent` through `consent` first, so a destructive write an applet asks\n * for is shown to the user and signed only on yes (kehto's runtime signs\n * applet publishes here and asks nobody). Without a window the shell is\n * signing for itself and the plain signer is returned.\n *\n * @param accounts - The shell's account manager.\n * @param consent - The gate from `createSigningConsent`.\n * @returns Hooks for `ShellAdapter.auth`.\n * @example\n * ```ts\n * const auth = createAuthHooks(accounts, consent);\n * auth.getUserPubkey(); // hex pubkey or null\n * await auth.getSigner('applet-1')?.signEvent?.(profileTemplate); // asks the user first\n * ```\n */\nexport function createAuthHooks(accounts: AccountManager, consent: SigningConsent): AuthHooks {\n return {\n getUserPubkey: () => accounts.active?.pubkey ?? null,\n getSigner(windowId?: string) {\n const account = accounts.active;\n if (!account || isReadOnlyAccount(account)) return null;\n const signer = wrapAccountSigner(account);\n if (windowId === undefined) return signer;\n return {\n ...signer,\n async signEvent(template) {\n await consent(windowId, template);\n return account.signEvent(template);\n },\n } satisfies Signer;\n },\n };\n}\n","import { lastValueFrom, map } from 'rxjs';\nimport type { EventStore } from 'applesauce-core';\nimport { getContacts, getInboxes, getOutboxes, getProfileContent } from 'applesauce-core/helpers';\nimport { createAddressLoader, type AddressPointerLoader } from 'applesauce-loaders/loaders';\nimport type { CacheRequest } from 'applesauce-loaders';\nimport type { IdentityServiceOptions } from '@kehto/services';\nimport type { NostrEvent } from '@napplet/core';\nimport type { RelayTiers } from '../types.js';\nimport type { ApplesaucePool } from './relay-hooks.js';\n\n/** The profile shape NAP-IDENTITY returns for `identity.getProfile`. */\nexport interface IdentityProfile {\n name?: string;\n displayName?: string;\n about?: string;\n picture?: string;\n banner?: string;\n nip05?: string;\n lud16?: string;\n website?: string;\n}\n\n/** Read/write flags per relay URL, as `identity.getRelays` reports them. */\nexport type RelayPermissions = Record<string, { read: boolean; write: boolean }>;\n\n/** The host-backed lookups kehto's identity service accepts, plus the relay list for the signer wrapper. */\nexport interface IdentityProviders extends Pick<IdentityServiceOptions, 'getProfile' | 'getFollows' | 'getMutes' | 'getList' | 'getZaps' | 'getBlocked' | 'getBadges'> {\n getRelays(pubkey: string): Promise<RelayPermissions>;\n}\n\n/** Options for {@link createIdentityProviders}. */\nexport interface IdentityProviderOptions {\n /** Loads replaceable events the store does not hold yet. */\n readonly loader?: AddressPointerLoader;\n}\n\nconst PROFILE = 0;\nconst FOLLOWS = 3;\nconst MUTES = 10000;\nconst RELAYS = 10002;\n\nfunction profileFrom(event: NostrEvent): IdentityProfile | null {\n const content = getProfileContent(event);\n if (!content) return null;\n const profile: IdentityProfile = {};\n if (content.name) profile.name = content.name;\n if (content.display_name) profile.displayName = content.display_name;\n if (content.about) profile.about = content.about;\n if (content.picture) profile.picture = content.picture;\n if (content.banner) profile.banner = content.banner;\n if (content.nip05) profile.nip05 = content.nip05;\n if (content.lud16) profile.lud16 = content.lud16;\n if (content.website) profile.website = content.website;\n return profile;\n}\n\nfunction relaysFrom(event: NostrEvent): RelayPermissions {\n const inboxes = new Set(getInboxes(event));\n const outboxes = new Set(getOutboxes(event));\n const relays: RelayPermissions = {};\n for (const url of [...inboxes, ...outboxes]) relays[url] = { read: inboxes.has(url), write: outboxes.has(url) };\n return relays;\n}\n\nfunction mutedPubkeys(event: NostrEvent): string[] {\n return event.tags.filter((tag) => tag[0] === 'p' && typeof tag[1] === 'string').map((tag) => tag[1] as string);\n}\n\n/**\n * Where a replaceable event is looked up when its pointer names no relay:\n * the discovery tier first, then the general tier. Indexers hold most\n * profiles and lists, but not all; the general servers catch the rest.\n *\n * @param config - The current tiers.\n * @returns Deduplicated relay URLs.\n * @example\n * ```ts\n * lookupRelaysOf(tiers.get()); // ['wss://purplepag.es', 'wss://relay.nos.social', 'wss://relay.damus.io', …]\n * ```\n */\nexport function lookupRelaysOf(config: ReturnType<RelayTiers['get']>): string[] {\n return [...new Set([...config.discovery, ...config.super])];\n}\n\n/**\n * The applesauce address loader kernl uses for replaceable and addressable\n * events the store does not hold: it asks the pointer's relays, then the\n * discovery and general tiers, and adds what it finds to the store.\n *\n * @param store - The shell's single event store.\n * @param pool - The shared applesauce pool.\n * @param tiers - Relay tiers; discovery and general are the lookup fallback.\n * @param cacheRequest - Asked before any relay, so a cached event shows at once; the relays are still asked for newer.\n * @returns A loader for {@link createIdentityProviders} and `lookupReplaceable`.\n * @example\n * ```ts\n * const loader = createReplaceableLoader(eventStore, pool, tiers);\n * const lookupBefore = lookupReplaceable(eventStore, { loader, relays: () => tiers.get().outbox });\n * ```\n */\nexport function createReplaceableLoader(store: EventStore, pool: ApplesaucePool, tiers: RelayTiers, cacheRequest?: CacheRequest): AddressPointerLoader {\n return createAddressLoader((relays, filters) => pool.request(relays, filters), {\n eventStore: store,\n lookupRelays: tiers.changes$.pipe(map(lookupRelaysOf)),\n ...(cacheRequest ? { cacheRequest } : {}),\n });\n}\n\n/**\n * Host-backed identity lookups for kehto's `createIdentityService`.\n *\n * Profile, follows, relays and mutes are read from the shell's `EventStore`\n * and, on a miss, loaded once through an applesauce address loader that asks\n * the discovery and general tiers. Lists, zaps, blocked keys and badges return the\n * spec-shaped empty value: kernl does not claim data it has not fetched.\n *\n * @param store - The shell's single event store.\n * @param pool - The shared applesauce pool.\n * @param tiers - Relay tiers; discovery and general serve misses.\n * @param options - Loader override for tests.\n * @returns Lookup callbacks keyed as kehto's options expect.\n * @example\n * ```ts\n * const providers = createIdentityProviders(eventStore, pool, tiers);\n * runtime.registerService('identity', createIdentityService({ getSigner, ...providers }));\n * ```\n */\nexport function createIdentityProviders(store: EventStore, pool: ApplesaucePool, tiers: RelayTiers, options: IdentityProviderOptions = {}): IdentityProviders {\n const loader = options.loader ?? createReplaceableLoader(store, pool, tiers);\n\n async function replaceable(kind: number, pubkey: string): Promise<NostrEvent | undefined> {\n const cached = store.getReplaceable(kind, pubkey);\n if (cached) return cached;\n const loaded = await lastValueFrom(loader({ kind, pubkey, relays: lookupRelaysOf(tiers.get()) }), { defaultValue: undefined });\n return loaded ?? store.getReplaceable(kind, pubkey);\n }\n\n return {\n getProfile: async (pubkey) => {\n const event = await replaceable(PROFILE, pubkey);\n return event ? profileFrom(event) : null;\n },\n getFollows: async (pubkey) => {\n const event = await replaceable(FOLLOWS, pubkey);\n return event ? getContacts(event).map((pointer) => pointer.pubkey) : [];\n },\n getMutes: async (pubkey) => {\n const event = await replaceable(MUTES, pubkey);\n return event ? mutedPubkeys(event) : [];\n },\n getRelays: async (pubkey) => {\n const event = await replaceable(RELAYS, pubkey);\n return event ? relaysFrom(event) : {};\n },\n getList: () => [],\n getZaps: () => [],\n getBlocked: () => [],\n getBadges: () => [],\n };\n}\n","import { AccountManager, type IAccount, type SerializedAccount } from 'applesauce-accounts';\nimport { registerCommonAccountTypes } from 'applesauce-accounts/accounts';\nimport type { StorageLike } from '../types.js';\nimport { createNamespacedStore } from '../persistence/store.js';\n\nconst ACCOUNTS_KEY = 'accounts:v1';\nconst ACTIVE_KEY = 'active-account:v1';\n\n/**\n * Account types whose serialised form carries a raw secret. `PrivateKeyAccount`\n * serialises the key itself and `SeedWordsAccount` the mnemonic. Neither may be\n * added to a kernl account manager: the only persisted form of a local key is\n * applesauce's `PasswordAccount`, whose `ncryptsec` is NIP-49 encrypted.\n *\n * @example\n * ```ts\n * PLAINTEXT_KEY_ACCOUNT_TYPES.includes(account.type); // true for 'nsec' and 'seed-words'\n * ```\n */\nexport const PLAINTEXT_KEY_ACCOUNT_TYPES: readonly string[] = Object.freeze(['nsec', 'seed-words']);\n\n/**\n * An `AccountManager` that refuses accounts whose persistence would write a\n * plaintext key, and persists the rest to kernl's storage.\n *\n * @example\n * ```ts\n * const manager = new KernlAccountManager();\n * manager.addAccount(PasswordAccount.fromNcryptsec(pubkey, ncryptsec));\n * manager.addAccount(PrivateKeyAccount.fromKey(secretKey)); // throws 'denied:plaintext-key-persistence'\n * ```\n */\nexport class KernlAccountManager extends AccountManager {\n /**\n * Add an account, refusing plaintext-key types.\n *\n * @param account - The account to add.\n * @throws `denied:plaintext-key-persistence` for `PrivateKeyAccount` and `SeedWordsAccount`.\n */\n override addAccount(account: IAccount): void {\n if (PLAINTEXT_KEY_ACCOUNT_TYPES.includes(account.type)) throw new Error('denied:plaintext-key-persistence');\n super.addAccount(account);\n }\n}\n\nfunction restore(manager: AccountManager, accounts: SerializedAccount[], activeId: string | null): void {\n const safe = accounts.filter((entry) => !PLAINTEXT_KEY_ACCOUNT_TYPES.includes(entry.type));\n manager.fromJSON(safe, true);\n if (activeId && manager.getAccount(activeId)) manager.setActive(activeId);\n}\n\n/**\n * Create the shell's account manager with the common applesauce account types\n * registered, state restored from `kernl:accounts:v1` and\n * `kernl:active-account:v1`, and every later change persisted.\n *\n * Keys live only inside applesauce signer instances: a `PrivateKeyAccount` is\n * refused at `addAccount` with `denied:plaintext-key-persistence`, and any such\n * entry found in storage is dropped on restore. Wrap a local key as a\n * `PasswordAccount` before adding it.\n *\n * @param storage - Where accounts and the active id are persisted.\n * @returns The account manager.\n * @example\n * ```ts\n * const accounts = createKernlAccounts(localStorage);\n * accounts.addAccount(PasswordAccount.fromNcryptsec(pubkey, ncryptsec));\n * accounts.setActive(accounts.accounts[0]!);\n * ```\n */\nexport function createKernlAccounts(storage: StorageLike): AccountManager {\n const store = createNamespacedStore(storage, 'kernl');\n const manager = new KernlAccountManager();\n registerCommonAccountTypes(manager);\n restore(manager, store.getJson<SerializedAccount[]>(ACCOUNTS_KEY, []), store.getJson<string | null>(ACTIVE_KEY, null));\n\n manager.accounts$.subscribe(() => {\n store.setJson(ACCOUNTS_KEY, manager.toJSON(true));\n });\n manager.active$.subscribe((account) => {\n if (account) store.setJson(ACTIVE_KEY, account.id);\n else store.remove(ACTIVE_KEY);\n });\n return manager;\n}\n","import { decodeAddressPointer, decodeEventPointer } from 'applesauce-core/helpers';\nimport type { AppletPointer } from '../types.js';\nimport { decodeBuiltin } from './builtin.js';\n\nconst HEX_64 = /^[0-9a-f]{64}$/;\nconst COORDINATE = /^([0-9a-f]{64}):(\\d+):(.*)$/s;\nconst A_TAG_COORDINATE = /^(\\d+):([0-9a-f]{64}):(.*)$/s;\n/** An encoded address anywhere in the text, so one copied as a link or inside a sentence still opens. */\nconst ENCODED = /(?:naddr|nevent|note)1[02-9ac-hj-np-z]+/i;\n\nfunction invalid(): never {\n throw new Error('invalid:pointer');\n}\n\nfunction relays(hints: readonly string[] | undefined): readonly string[] {\n return Object.freeze([...(hints ?? [])]);\n}\n\nfunction fromCoordinate(pubkey: string, kind: string, identifier: string): AppletPointer {\n return { kind: 'address', pubkey, identifier, eventKind: Number(kind), relays: Object.freeze([]) };\n}\n\nfunction fromBech32(input: string): AppletPointer | undefined {\n if (input.startsWith('naddr1')) {\n const pointer = decodeAddressPointer(input);\n if (!pointer) invalid();\n return { kind: 'address', pubkey: pointer.pubkey, identifier: pointer.identifier, eventKind: pointer.kind, relays: relays(pointer.relays) };\n }\n if (input.startsWith('nevent1') || input.startsWith('note1')) {\n const pointer = decodeEventPointer(input);\n if (!pointer) invalid();\n return pointer.author\n ? { kind: 'event', id: pointer.id, relays: relays(pointer.relays), author: pointer.author }\n : { kind: 'event', id: pointer.id, relays: relays(pointer.relays) };\n }\n return undefined;\n}\n\n/**\n * Decode what a user typed or clicked into the event to fetch.\n *\n * Accepts `naddr1…`, `nevent1…`, `note1…`, a bare 64-hex event id, any of\n * those behind a `nostr:` prefix, and plain coordinates in either\n * `<pubkey>:<kind>:<identifier>` or NIP-01 `<kind>:<pubkey>:<identifier>`\n * order. An encoded address is also found inside a link or a sentence, since\n * that is how addresses are shared. The result says which event to fetch and\n * nothing more; trust comes from verifying that event, never from the pointer.\n *\n * @param input - The address text.\n * @returns The decoded pointer.\n * @throws `invalid:pointer` for anything else.\n * @example\n * ```ts\n * decodePointer('nostr:naddr1…').kind; // 'address'\n * decodePointer(`${pubkey}:35129:chat`); // { kind: 'address', pubkey, identifier: 'chat', eventKind: 35129, relays: [] }\n * decodePointer('https://applets.example/n/naddr1…?ref=share').kind; // 'address'\n * ```\n */\nexport function decodePointer(input: string): AppletPointer {\n const text = input.trim().replace(/^nostr:/i, '');\n const builtin = decodeBuiltin(text);\n if (builtin) return builtin;\n if (HEX_64.test(text)) return { kind: 'event', id: text, relays: Object.freeze([]) };\n\n const coordinate = COORDINATE.exec(text);\n if (coordinate) return fromCoordinate(coordinate[1] as string, coordinate[2] as string, coordinate[3] as string);\n const aTag = A_TAG_COORDINATE.exec(text);\n if (aTag) return fromCoordinate(aTag[2] as string, aTag[1] as string, aTag[3] as string);\n\n return fromBech32((ENCODED.exec(text)?.[0] ?? text).toLowerCase()) ?? invalid();\n}\n","import type { NappletManifest } from '@kehto/nip/5d';\nimport type { AppletPointer, AppletSummary, BuiltinApplet } from '../types.js';\nimport type { ResolvedApplet } from './resolve.js';\n\n/**\n * The key shown as the publisher of an applet nobody published. A manifest's catalogue id needs\n * a key, and the all-zero one cannot sign, so it can never collide with a real publisher.\n *\n * @example\n * ```ts\n * summary.builtin && summary.publisher === BUILTIN_PUBLISHER; // true\n * ```\n */\nexport const BUILTIN_PUBLISHER: string = '0'.repeat(64);\n\nconst ADDRESS = /^kernl:([a-z][a-z0-9-]*)$/;\nconst MANIFEST_KIND = 35129;\n\n/**\n * The address of an applet that comes with the shell.\n *\n * @param id - The built-in applet's name.\n * @returns `kernl:<id>`.\n * @example\n * ```ts\n * builtinAddress('messages'); // 'kernl:messages'\n * ```\n */\nexport function builtinAddress(id: string): string {\n return `kernl:${id}`;\n}\n\n/**\n * Read a `kernl:<id>` address.\n *\n * @param text - A trimmed address.\n * @returns A built-in pointer, or `undefined` when the text is not one.\n * @example\n * ```ts\n * decodeBuiltin('kernl:messages'); // { kind: 'builtin', id: 'messages', relays: [] }\n * ```\n */\nexport function decodeBuiltin(text: string): AppletPointer | undefined {\n const id = ADDRESS.exec(text)?.[1];\n return id === undefined ? undefined : { kind: 'builtin', id, relays: Object.freeze([]) };\n}\n\nasync function sha256Hex(text: string): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text));\n return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, '0')).join('');\n}\n\nfunction manifestOf(applet: BuiltinApplet): NappletManifest {\n const archetypes = (applet.archetypes ?? []).map((entry) => ({ slug: entry.slug, convention: entry.convention, params: [...(entry.params ?? [])] }));\n return {\n format: 'current',\n artifactHash: applet.sha256,\n optional: [...applet.optional],\n archetypeSlugs: [...new Set(archetypes.map((entry) => entry.slug))],\n intents: archetypes.map((entry) => ({ identity: entry.convention, parameters: entry.params })),\n kind: MANIFEST_KIND,\n pubkey: BUILTIN_PUBLISHER,\n dTag: applet.id,\n catalogId: `nip5d:${MANIFEST_KIND}:${BUILTIN_PUBLISHER}:${applet.id}`,\n paths: [{ path: '/index.html', sha256: applet.sha256 }],\n aggregateHash: applet.sha256,\n servers: [],\n requires: [...applet.requires],\n archetypes,\n title: applet.title,\n description: applet.description,\n };\n}\n\nfunction summaryOf(applet: BuiltinApplet): AppletSummary {\n const manifest = manifestOf(applet);\n return {\n identity: { dTag: applet.id, hash: applet.sha256 },\n address: builtinAddress(applet.id),\n title: applet.title,\n description: applet.description,\n publisher: BUILTIN_PUBLISHER,\n requires: Object.freeze([...applet.requires]),\n optional: Object.freeze([...applet.optional]),\n archetypes: Object.freeze([...(manifest.archetypeSlugs as string[])]),\n builtin: true,\n manifest,\n };\n}\n\n/**\n * Load an applet that comes with the shell and check it against its pinned hash.\n *\n * Nothing is fetched from the network and no signature is checked: the host that\n * lists the applet is the page the user already trusts with everything else, so\n * what it pins is as trusted as its own code. The check is that the bytes loaded\n * are the bytes pinned. The summary is shaped like a published applet's, so\n * grants, intents and the mount plan treat it the same.\n *\n * @param builtins - The applets the host ships.\n * @param id - The name from a `kernl:<id>` address.\n * @returns The summary and the verified `index.html`.\n * @throws `invalid:pointer` for a name the host does not ship, `unavailable:blob` when the\n * artifact cannot be loaded, `invalid:artifact-hash` when it does not match its pin.\n * @example\n * ```ts\n * const { summary, indexHtml } = await resolveBuiltin(builtins, 'messages');\n * summary.address; // 'kernl:messages'\n * ```\n */\nexport async function resolveBuiltin(builtins: readonly BuiltinApplet[], id: string): Promise<ResolvedApplet> {\n const applet = builtins.find((candidate) => candidate.id === id);\n if (!applet) throw new Error('invalid:pointer');\n const indexHtml = await applet.load().catch(() => {\n throw new Error('unavailable:blob');\n });\n if ((await sha256Hex(indexHtml)) !== applet.sha256) throw new Error('invalid:artifact-hash');\n return { summary: summaryOf(applet), indexHtml };\n}\n","import { filter, lastValueFrom, map, merge, switchMap, take, timer, toArray, type Observable, type OperatorFunction } from 'rxjs';\nimport {\n NappletResolutionError,\n openNappletArtifactCache,\n resolveNapplet,\n type NappletArtifactCache,\n type ResolveNappletOptions,\n type ResolvedNapplet,\n} from '@kehto/nip/5d';\nimport type { NostrEvent, NostrFilter } from '@napplet/core';\nimport type { AppletPointer, AppletSummary, RelayTiers } from '../types.js';\nimport { asFilters, type ApplesaucePool } from '../applesauce/relay-hooks.js';\nimport { addressOf } from '../catalog/entry.js';\n\n/**\n * Milliseconds a blob server gets before the next one is tried.\n *\n * @example\n * ```ts\n * await fetch(`${server}/${sha256}`, { signal: AbortSignal.timeout(BLOB_TIMEOUT_MS) }); // 20 s per server\n * ```\n */\nexport const BLOB_TIMEOUT_MS = 20_000;\n\n/** A pointer to something published: a built-in applet is never looked up. */\nexport type PublishedPointer = Exclude<AppletPointer, { kind: 'builtin' }>;\n\nfunction filterFor(pointer: PublishedPointer): NostrFilter {\n if (pointer.kind === 'event') return { ids: [pointer.id] };\n const filter: NostrFilter = { kinds: [pointer.eventKind], authors: [pointer.pubkey] };\n if (pointer.identifier !== '') filter['#d'] = [pointer.identifier];\n return filter;\n}\n\n/**\n * How long a manifest lookup waits, in milliseconds.\n *\n * `settleMs` runs from the first manifest, so a slower relay holding a newer\n * release can still answer. `patienceMs` runs from the first relay that\n * answers with nothing, so a slower relay that does hold the applet is not cut\n * off. `timeoutMs` bounds a round of asking when no relay answers at all; a\n * lookup is at most two rounds. `retryDelayMs` is the pause before a round\n * whose relays all refused at once is asked a second time.\n */\nexport interface ManifestTiming {\n readonly settleMs: number;\n readonly patienceMs: number;\n readonly timeoutMs: number;\n readonly retryDelayMs: number;\n}\n\n/**\n * The waits {@link fetchManifestEvent} uses unless told otherwise.\n *\n * @example\n * ```ts\n * MANIFEST_TIMING.timeoutMs; // 10000: the longest one round of asking can take\n * await fetchManifestEvent(pool, tiers, pointer, { patienceMs: 2_000 });\n * ```\n */\nexport const MANIFEST_TIMING: ManifestTiming = Object.freeze({ settleMs: 3_000, patienceMs: 8_000, timeoutMs: 10_000, retryDelayMs: 1_000 });\n\n\n/**\n * Relay URLs worth dialling, each once and in one spelling. Hints inside a\n * pointer are text a stranger wrote, so one that is not a websocket URL is\n * dropped instead of failing the lookup.\n */\nfunction dialable(urls: readonly string[]): string[] {\n const kept = new Map<string, string>();\n for (const url of urls) {\n if (!/^wss?:\\/\\//i.test(url) || !URL.canParse(url)) continue;\n const key = new URL(url).href;\n if (!kept.has(key)) kept.set(key, url);\n }\n return [...kept.values()];\n}\n\n/**\n * When the manifest request may stop before every relay has answered.\n *\n * applesauce's default stops three seconds after the first relay reports the\n * end of its stored events, found or not. A catalogue relay slower than a\n * general relay with nothing to say then loses the race and the applet reads\n * as missing. So the two cases get their own clocks: once a manifest is in,\n * the rest have `settleMs` to offer a newer one; once a relay has answered\n * with nothing, the rest have the longer `patienceMs` to do better. A relay\n * that accepts a connection and hangs up never answers either way, and\n * applesauce-relay 7 leaves it pending whatever `reconnect` or\n * `firstResponseTimeout` say, which is why the request also carries\n * `timeoutMs`.\n */\nfunction settleManifestRequest(timing: ManifestTiming): OperatorFunction<{ type: string }, boolean> {\n const after = (messages: Observable<{ type: string }>, type: string, waitMs: number): Observable<number> =>\n messages.pipe(filter((message) => message.type === type), take(1), switchMap(() => timer(waitMs)));\n return (messages) => merge(after(messages, 'EVENT', timing.settleMs), after(messages, 'EOSE', timing.patienceMs)).pipe(map(() => true));\n}\n\n/** What one round of asking produced: the newest manifest, and whether any relay answered at all. */\ninterface Asked {\n readonly newest?: NostrEvent;\n readonly answered: boolean;\n /** True when every relay refused outright, as opposed to the round running out its clock in silence. */\n readonly refused?: boolean;\n}\n\nasync function askOnce(pool: ApplesaucePool, relays: string[], filter: NostrFilter, waits: ManifestTiming): Promise<Asked> {\n const request = pool.request(relays, asFilters([filter]), { complete: settleManifestRequest(waits), timeout: waits.timeoutMs });\n try {\n const events = await lastValueFrom(request.pipe(toArray()), { defaultValue: [] });\n const newest = events.reduce<NostrEvent | undefined>((best, event) => (best && best.created_at >= event.created_at ? best : event), undefined);\n return newest ? { newest, answered: true } : { answered: true };\n } catch (error) {\n // Every relay failed, or none answered in time: the network could not say, which is not \"no such applet\".\n return { answered: false, refused: (error as Error).name !== 'TimeoutError' };\n }\n}\n\n/**\n * One round: ask the relays, and ask once more when every one of them refused\n * the connection. Busy public relays answer a websocket upgrade with 502 or\n * 503 for a moment and accept the next one, and applesauce-relay 7 fails a\n * relay on its first refused connection whatever `reconnect` says. A round\n * that ran out its clock is not asked again: it already waited.\n */\nasync function askRelays(pool: ApplesaucePool, relays: string[], filter: NostrFilter, waits: ManifestTiming): Promise<Asked> {\n const first = await askOnce(pool, relays, filter, waits);\n if (!first.refused) return first;\n await new Promise((resolve) => setTimeout(resolve, waits.retryDelayMs));\n return askOnce(pool, relays, filter, waits);\n}\n\n/**\n * Fetch the manifest event a pointer names.\n *\n * The relays the address names and the `apps` tier are asked first. When they\n * do not produce the manifest, whether because they do not hold it or because\n * none of them answered, the `super` tier is asked before giving up: a\n * manifest is an ordinary event, authors publish it to general relays too, and\n * an address that opens elsewhere should not fail here because one catalogue\n * relay had a bad minute. For addresses, the newest event wins, since a named\n * applet is an addressable event that its author replaces on every release. A\n * relay that is down, silent or hangs up does not fail the lookup while\n * another one answers, a round whose relays all refused at once is asked a\n * second time, and hints that are not relay URLs are ignored.\n *\n * @param pool - The shared applesauce pool.\n * @param tiers - Relay tiers; `apps` is asked first, `super` as the fallback.\n * @param pointer - The decoded pointer.\n * @param timing - Overrides for {@link MANIFEST_TIMING}, applied to each round.\n * @returns The manifest event, unverified.\n * @throws `unavailable:manifest` when a relay answered and none had it, or\n * there was no relay to ask; `unavailable:network` when no relay answered.\n * @example\n * ```ts\n * const event = await fetchManifestEvent(pool, tiers, decodePointer('naddr1…'));\n * ```\n */\nexport async function fetchManifestEvent(pool: ApplesaucePool, tiers: RelayTiers, pointer: PublishedPointer, timing: Partial<ManifestTiming> = {}): Promise<NostrEvent> {\n const config = tiers.get();\n const first = dialable([...pointer.relays, ...config.apps]);\n const rounds = [first, dialable([...first, ...config.super]).slice(first.length)].filter((relays) => relays.length > 0);\n const waits = { ...MANIFEST_TIMING, ...timing };\n const filter = filterFor(pointer);\n let answered = rounds.length === 0;\n for (const relays of rounds) {\n const asked = await askRelays(pool, relays, filter, waits);\n if (asked.newest) return asked.newest;\n answered ||= asked.answered;\n }\n throw new Error(answered ? 'unavailable:manifest' : 'unavailable:network');\n}\n\n/**\n * Fetch an artifact blob by trying each server in turn with a 20-second budget.\n *\n * Bytes are returned unverified; `resolveNapplet` hashes them. Gateways are\n * accelerators, never identity.\n *\n * @param sha256 - The blob hash, lowercase hex.\n * @param servers - Server base URLs from the manifest.\n * @param fetchImpl - The fetch to use; the global one by default.\n * @returns The bytes the first responsive server returned.\n * @throws `unavailable:blob` when every server failed.\n * @example\n * ```ts\n * const bytes = await defaultFetchBlob(hash, ['https://blossom.example']);\n * ```\n */\nexport async function defaultFetchBlob(sha256: string, servers: readonly string[], fetchImpl: typeof fetch = fetch): Promise<Uint8Array> {\n for (const server of servers) {\n try {\n const response = await fetchImpl(`${server.replace(/\\/+$/, '')}/${sha256}`, { signal: AbortSignal.timeout(BLOB_TIMEOUT_MS) });\n if (response.ok) return new Uint8Array(await response.arrayBuffer());\n } catch {\n // The next server gets its turn; a dead gateway is not a verification failure.\n }\n }\n throw new Error('unavailable:blob');\n}\n\n/**\n * Reduce a verified napplet to what the shell shows before running it.\n *\n * @param resolved - The output of kehto's `resolveNapplet`.\n * @param address - The shareable address of the manifest event.\n * @returns The summary; `requires` and `optional` are advisory, never grants.\n * @example\n * ```ts\n * summarize(resolved, 'naddr1…').identity; // { dTag: 'chat', hash: '…' }\n * ```\n */\nexport function summarize(resolved: ResolvedNapplet, address: string): AppletSummary {\n const { manifest } = resolved;\n const summary: AppletSummary = {\n identity: { dTag: resolved.dTag, hash: resolved.aggregateHash },\n address,\n title: manifest.title ?? (resolved.dTag || 'Untitled applet'),\n description: manifest.description ?? '',\n publisher: manifest.pubkey,\n requires: Object.freeze([...manifest.requires]),\n optional: Object.freeze([...(manifest.optional ?? [])]),\n archetypes: Object.freeze([...(manifest.archetypeSlugs ?? manifest.archetypes.map((entry) => entry.slug))]),\n manifest,\n ...(manifest.icon ? { icon: manifest.icon } : {}),\n ...(manifest.source ? { source: manifest.source } : {}),\n };\n return summary;\n}\n\n/**\n * Open kehto's verified-artifact cache over Cache Storage when the page has\n * it, and nothing otherwise. Cached bytes are re-hashed on every read by\n * `resolveNapplet`, so the cache accelerates and never authenticates.\n *\n * @returns The cache, or undefined where Cache Storage is unavailable.\n * @example\n * ```ts\n * const cache = await openDefaultArtifactCache();\n * ```\n */\nexport async function openDefaultArtifactCache(): Promise<NappletArtifactCache | undefined> {\n if (typeof caches === 'undefined') return undefined;\n return openNappletArtifactCache({ cacheStorage: caches, requireStorageEstimate: false });\n}\n\n/** Inputs for {@link resolveApplet}. */\nexport interface ResolveAppletOptions {\n readonly event: NostrEvent;\n readonly fetchBlob: (sha256: string, servers: readonly string[]) => Promise<Uint8Array>;\n readonly cache?: NappletArtifactCache;\n /** Relay hints carried in the summary's address. */\n readonly relays?: readonly string[];\n}\n\n/** A verified applet: what to show and what to run. */\nexport interface ResolvedApplet {\n readonly summary: AppletSummary;\n /** The verified `index.html` text, before CSP and prelude insertion. */\n readonly indexHtml: string;\n}\n\nfunction reasonFor(error: NappletResolutionError): string {\n return error.code === 'blob-unavailable' ? 'unavailable:blob' : `invalid:${error.code}`;\n}\n\n/**\n * Verify a manifest event and its artifact through kehto's `resolveNapplet`.\n *\n * Resolution failures are rethrown with kernl's prefixed reasons: a missing\n * blob is `unavailable:blob`; a bad signature, manifest, hash or index is\n * `invalid:<code>` with kehto's code.\n *\n * @param options - Manifest event, blob fetcher and optional verified-artifact cache.\n * @returns The summary and verified index HTML.\n * @example\n * ```ts\n * const { summary, indexHtml } = await resolveApplet({ event, fetchBlob: defaultFetchBlob });\n * ```\n */\nexport async function resolveApplet(options: ResolveAppletOptions): Promise<ResolvedApplet> {\n const input: ResolveNappletOptions = { event: options.event, fetchBlob: options.fetchBlob };\n if (options.cache) input.cache = options.cache;\n try {\n const resolved = await resolveNapplet(input);\n return { summary: summarize(resolved, addressOf(options.event, options.relays)), indexHtml: resolved.indexHtml };\n } catch (error) {\n if (error instanceof NappletResolutionError) throw new Error(reasonFor(error));\n throw error;\n }\n}\n","import { naddrEncode, neventEncode } from 'applesauce-core/helpers';\nimport { NAPPLET_KIND_SNAPSHOT, parseNappletManifest, verifyManifestSignature, type NappletManifest } from '@kehto/nip/5d';\nimport type { NostrEvent } from '@napplet/core';\n\n/** One applet as the store lists it. Read from a signed manifest; its bytes are verified only when it is opened. */\nexport interface CatalogEntry {\n /** kehto's publisher- and kind-safe identity; the same id the intent catalogue uses. */\n readonly catalogId: string;\n /** A shareable address the launcher can decode: `naddr1…`, or `nevent1…` for a pinned version. */\n readonly address: string;\n readonly kind: number;\n readonly publisher: string;\n readonly title: string;\n readonly description: string;\n /** Lower-cased topics from the manifest's `t` tags. */\n readonly topics: readonly string[];\n readonly requires: readonly string[];\n /** Roles from `z` tags. */\n readonly archetypes: readonly string[];\n /** Accepted convention identities from `i` tags, such as `napplet:profile/open`. */\n readonly conventions: readonly string[];\n /** A display URL for the icon, from the manifest's first server. Never identity. */\n readonly iconUrl?: string;\n readonly publishedAt: number;\n}\n\nconst unique = (values: readonly string[]): readonly string[] => Object.freeze([...new Set(values)]);\n\nfunction topicsOf(event: NostrEvent): readonly string[] {\n return unique(event.tags.filter((tag) => tag[0] === 't' && typeof tag[1] === 'string' && tag[1].trim() !== '').map((tag) => (tag[1] as string).trim().toLowerCase()));\n}\n\nfunction iconUrlOf(manifest: NappletManifest): string | undefined {\n const server = manifest.servers[0];\n return manifest.icon && server ? `${server.replace(/\\/+$/, '')}/${manifest.icon.sha256}` : undefined;\n}\n\n/**\n * The address a person can paste back into the launcher for this manifest.\n *\n * @param event - A napplet manifest event.\n * @param relays - Where it was found; carried as hints, never as identity.\n * @returns `nevent1…` for a snapshot, `naddr1…` for a root or named applet.\n * @example\n * ```ts\n * addressOf(manifest, ['wss://relay.napplet.soy']); // 'naddr1…'\n * ```\n */\nexport function addressOf(event: NostrEvent, relays: readonly string[] = []): string {\n if (event.kind === NAPPLET_KIND_SNAPSHOT) return neventEncode({ id: event.id, author: event.pubkey, kind: event.kind, relays: [...relays] });\n const identifier = event.tags.find((tag) => tag[0] === 'd')?.[1] ?? '';\n return naddrEncode({ kind: event.kind, pubkey: event.pubkey, identifier, relays: [...relays] });\n}\n\n/**\n * Read a store entry from a manifest event.\n *\n * The signature is checked so a relay cannot list an applet under someone\n * else's name; the artifact is not fetched. Malformed manifests yield nothing.\n *\n * @param event - A candidate manifest event.\n * @param relays - Relay hints for the entry's address.\n * @returns The entry, or undefined when the event is not a valid signed manifest.\n * @example\n * ```ts\n * toCatalogEntry(event)?.topics; // ['game', 'puzzle']\n * ```\n */\nexport function toCatalogEntry(event: NostrEvent, relays: readonly string[] = []): CatalogEntry | undefined {\n let manifest: NappletManifest;\n try {\n if (!verifyManifestSignature(event)) return undefined;\n manifest = parseNappletManifest(event);\n } catch {\n return undefined;\n }\n const iconUrl = iconUrlOf(manifest);\n return Object.freeze({\n catalogId: manifest.catalogId,\n address: addressOf(event, relays),\n kind: event.kind,\n publisher: event.pubkey,\n title: manifest.title ?? (manifest.dTag || 'Untitled applet'),\n description: manifest.description ?? '',\n topics: topicsOf(event),\n requires: unique(manifest.requires),\n archetypes: unique(manifest.archetypeSlugs ?? manifest.archetypes.map((entry) => entry.slug)),\n conventions: unique(manifest.archetypes.map((entry) => entry.convention)),\n ...(iconUrl ? { iconUrl } : {}),\n publishedAt: event.created_at,\n });\n}\n\n/**\n * Keep the newest entry per catalogue id, newest first.\n *\n * Named and root applets are replaced on every release, so relays may hold\n * several versions; the store lists one.\n *\n * @param entries - Entries in any order, possibly repeated.\n * @returns One entry per applet.\n * @example\n * ```ts\n * newestEntries([older, newer]); // [newer]\n * ```\n */\nexport function newestEntries(entries: readonly CatalogEntry[]): readonly CatalogEntry[] {\n const newest = new Map<string, CatalogEntry>();\n for (const entry of entries) {\n const current = newest.get(entry.catalogId);\n if (!current || entry.publishedAt > current.publishedAt) newest.set(entry.catalogId, entry);\n }\n return Object.freeze([...newest.values()].sort((a, b) => b.publishedAt - a.publishedAt));\n}\n","import {\n assertNappletHasNoFrame,\n prepareNappletSrcdoc,\n renderNappletCspMeta,\n renderNappletNamespacePrelude,\n resolveShellEnvironment,\n type NappletCspDirectives,\n type NappletCspOptions,\n type NappletExperimentalOptions,\n type ShellAdapter,\n} from '@kehto/shell';\nimport { createAppletCsp, renderInsertionLockScript, type GuardProfile } from '@kernlize/guard';\nimport { renderRandomUuidFallbackScript } from '../crypto/install.js';\nimport type { AppletSummary, MountPlan } from '../types.js';\n\n/** Inputs for {@link planMount}. */\nexport interface PlanMountOptions {\n readonly summary: AppletSummary;\n /** Verified `index.html` text from {@link resolveApplet}. */\n readonly indexHtml: string;\n /** The live shell wiring; decides which domains exist at all. */\n readonly adapter: ShellAdapter;\n readonly guardProfile: GuardProfile;\n readonly windowId: string;\n}\n\n/**\n * Replace the first occurrence of `find` in `text`, refusing when it is absent.\n *\n * @param text - The text to edit.\n * @param find - The exact substring to replace.\n * @param replacement - What takes its place.\n * @returns The edited text.\n * @throws `Error('unavailable:frame-lock')` when `find` does not occur.\n * @example\n * ```ts\n * spliceOnce('a<b>c', '<b>', '<b><i>'); // 'a<b><i>c'\n * ```\n */\nexport function spliceOnce(text: string, find: string, replacement: string): string {\n const at = text.indexOf(find);\n if (at === -1) throw new Error('unavailable:frame-lock');\n return `${text.slice(0, at)}${replacement}${text.slice(at + find.length)}`;\n}\n\n/** kehto's nested-context lock: Trusted Types directives in the CSP, the policy and factory pins in the prelude. */\nconst NESTED_CONTEXT_LOCK: NappletExperimentalOptions = Object.freeze({ nestedContextLock: true });\n\n/**\n * Refuse verified markup that declares a nested frame, with kernl's stable\n * reason in place of kehto's message.\n *\n * @param html - Verified applet HTML.\n * @throws `Error('denied:nested-frame')` when kehto's scan finds a frame element.\n */\nfunction assertNoFrame(html: string): void {\n try {\n assertNappletHasNoFrame(html);\n } catch {\n throw new Error('denied:nested-frame');\n }\n}\n\n/**\n * Insert kernl's insertion lock (D-014) immediately after the CSP meta and\n * locked namespace prelude kehto put first in `<head>`, before any applet\n * script, followed by the `randomUUID` fallback (D-024) the prelude needs when\n * the shell is not a secure context. `@kehto/shell` has no hook for a second\n * prelude, so the pair is re-rendered and located in the srcdoc.\n */\nfunction addInsertionLock(srcdoc: string, csp: NappletCspOptions, domains: readonly string[]): string {\n const head = renderNappletCspMeta(csp, true) + renderNappletNamespacePrelude({ domains, experimental: NESTED_CONTEXT_LOCK });\n return spliceOnce(srcdoc, head, head + renderInsertionLockScript() + renderRandomUuidFallbackScript());\n}\n\n/**\n * Build everything `mountApplet` needs, without touching the DOM.\n *\n * The environment is kehto's `resolveShellEnvironment`, so it is the live\n * domains narrowed by the host's `capabilities.resolveEnvironment` (kernl's\n * grants). The CSP is the guard's zero-network profile, inserted first in\n * `<head>` by `prepareNappletSrcdoc` with kehto's nested-context lock enabled\n * (`experimental.nestedContextLock`): the policy gains kehto's Trusted Types\n * directives and the mandatory namespace prelude installs kehto's creation\n * lock. kernl's insertion lock follows the prelude. Markup that declares a\n * nested frame is refused by kehto's scan before any of that (D-014).\n * `missingRequired` lists what the applet asked for and will not get, so the\n * host can warn before mounting.\n *\n * @param options - Summary, verified HTML, adapter, guard profile and window id.\n * @returns A plan whose `srcdoc` is ready to assign.\n * @throws `Error('denied:nested-frame')` when the verified markup declares a frame element.\n * @throws `Error('unavailable:frame-lock')` when kehto's head cannot be found to place the insertion lock.\n * @example\n * ```ts\n * const plan = planMount({ summary, indexHtml, adapter, guardProfile: 'strict', windowId: 'w1' });\n * plan.sandbox; // 'allow-scripts'\n * ```\n */\nexport function planMount(options: PlanMountOptions): MountPlan {\n const { summary } = options;\n assertNoFrame(options.indexHtml);\n const environment = resolveShellEnvironment(options.adapter, { dTag: summary.identity.dTag, aggregateHash: summary.identity.hash });\n const domains = environment.capabilities.domains;\n const guardCsp = createAppletCsp(options.guardProfile);\n const csp: NappletCspOptions = { connectOrigins: guardCsp.connectOrigins, directives: guardCsp.directives as NappletCspDirectives };\n return {\n windowId: options.windowId,\n summary,\n srcdoc: addInsertionLock(prepareNappletSrcdoc(options.indexHtml, { domains, csp, experimental: NESTED_CONTEXT_LOCK }), csp, domains),\n sandbox: 'allow-scripts',\n environment,\n missingRequired: Object.freeze(summary.requires.filter((domain) => !domains.includes(domain))),\n };\n}\n","import { BehaviorSubject } from 'rxjs';\nimport { denyNappletControllerAccess, type OriginRegistry, type ShellBridge } from '@kehto/shell';\nimport type { WindowVisibility } from '@kernlize/guard';\nimport type { AppletHandle, AppletStatus, FrameLike, MountPlan } from '../types.js';\n\n/**\n * The Permissions-Policy `denyNappletControllerAccess` sets, for frames that cannot report their own.\n *\n * @example\n * ```ts\n * frame.setAttribute('allow', CONTROLLER_DENY_POLICY); // \"gamepad 'none'; hid 'none'; usb 'none'\"\n * ```\n */\nexport const CONTROLLER_DENY_POLICY = \"gamepad 'none'; hid 'none'; usb 'none'\";\n\n/** What the guard needs to know about a mounted window. */\nexport interface MountGuardHooks {\n setVisibility(windowId: string, visibility: WindowVisibility): void;\n /** Drop every queue and counter for the window. */\n forget(windowId: string): void;\n}\n\n/** Dependencies for {@link mountApplet}. */\nexport interface MountDeps {\n readonly bridge: Pick<ShellBridge, 'observeFrame' | 'revokeNapplet'>;\n readonly originRegistry: Pick<OriginRegistry, 'register' | 'setEnvironment' | 'unregister'>;\n readonly guard: MountGuardHooks;\n /** Called after the frame was removed because the bridge revoked the binding. */\n readonly onRevoked?: (windowId: string, reason: string) => void;\n}\n\n/** An {@link AppletHandle} with the entry point the bridge's revocation hook calls. */\nexport interface MountedApplet extends AppletHandle {\n /** Mark the applet revoked and remove its frame. Idempotent with `close`. */\n revoked(reason: string): void;\n}\n\nfunction hasGetAttribute(frame: FrameLike): frame is FrameLike & { getAttribute(name: string): string | null } {\n return typeof (frame as { getAttribute?: unknown }).getAttribute === 'function';\n}\n\nfunction harden(frame: FrameLike): void {\n // The attribute is replaced, not added to: a token the host left on the frame, such as allow-same-origin, would widen the sandbox (AGENTS.md, security posture).\n frame.setAttribute('sandbox', 'allow-scripts');\n if (hasGetAttribute(frame)) denyNappletControllerAccess(frame);\n else frame.setAttribute('allow', CONTROLLER_DENY_POLICY);\n}\n\n/**\n * Put a planned applet into a frame, in the NIP-5D order the shell depends on:\n * harden the frame, register its window with the verified identity, freeze its\n * environment, start watching for a second load, then assign `srcdoc`. The\n * status moves to `running` on the frame's first load.\n *\n * `close()` revokes the binding through the bridge, which closes the port and\n * destroys sessions and grants, then removes the frame. When the bridge revokes\n * the binding on its own, `revoked()` removes the frame and tells the host. The\n * frame is removed on every revocation reason; it is never reused.\n *\n * @param plan - The plan from {@link planMount}.\n * @param frame - An iframe, or any object with its shape, already in the DOM.\n * @param deps - Bridge, origin registry, guard hooks and the host's revocation callback.\n * @returns The running applet's handle.\n * @throws `invalid:frame-detached` when the frame has no `contentWindow`.\n * @example\n * ```ts\n * const handle = mountApplet(plan, iframe, { bridge, originRegistry, guard, onRevoked });\n * handle.setVisibility({ visible: true, focused: true });\n * handle.close();\n * ```\n */\nexport function mountApplet(plan: MountPlan, frame: FrameLike, deps: MountDeps): MountedApplet {\n const win = frame.contentWindow;\n if (!win) throw new Error('invalid:frame-detached');\n const { windowId } = plan;\n const status$ = new BehaviorSubject<AppletStatus>('mounting');\n let finished = false;\n\n harden(frame);\n deps.originRegistry.register(win, windowId, { dTag: plan.summary.identity.dTag, aggregateHash: plan.summary.identity.hash });\n deps.originRegistry.setEnvironment(win, plan.environment);\n const stopObserving = deps.bridge.observeFrame(frame, windowId);\n const onFirstLoad = (): void => {\n frame.removeEventListener('load', onFirstLoad);\n status$.next('running');\n };\n frame.addEventListener('load', onFirstLoad);\n frame.srcdoc = plan.srcdoc;\n\n const teardown = (status: AppletStatus): void => {\n finished = true;\n stopObserving();\n frame.removeEventListener('load', onFirstLoad);\n frame.remove();\n deps.guard.forget(windowId);\n status$.next(status);\n };\n\n return {\n windowId,\n summary: plan.summary,\n status$,\n get status() {\n return status$.value;\n },\n setVisibility: (visibility) => deps.guard.setVisibility(windowId, visibility),\n close() {\n if (finished) return;\n finished = true;\n deps.bridge.revokeNapplet(windowId, 'host');\n deps.originRegistry.unregister(windowId);\n teardown('closed');\n },\n revoked(reason) {\n if (finished) return;\n teardown('revoked');\n deps.onRevoked?.(windowId, reason);\n },\n };\n}\n","import { BehaviorSubject, type Observable } from 'rxjs';\nimport type { NappletMessageDecision } from '@kehto/shell';\nimport {\n classifyEnvelope,\n createFocusFirewall,\n createGuardConfig,\n createIngressGuard,\n createVisibilityGate,\n estimateEnvelopeSize,\n type AdmitOptions,\n type FocusFirewall,\n type GuardConfig,\n type GuardDisposition,\n type GuardEnvelope,\n type GuardEvent,\n type GuardProfile,\n type IngressGuard,\n type OpClass,\n type VisibilityGate,\n type WindowVisibility,\n} from '@kernlize/guard';\n\n/** The window a message came from, as the shell resolved it. Never taken from the message. */\nexport interface WindowResolution {\n readonly windowId: string;\n readonly napplet: string;\n}\n\n/** Options for {@link createGuardPipeline}. */\nexport interface GuardPipelineOptions {\n readonly config: GuardConfig;\n readonly now?: () => number;\n /** Receives every guard event from every layer. */\n readonly onEvent?: (event: GuardEvent) => void;\n /** Called once when a window crosses the quarantine threshold; kernl revokes it here, before the triggering envelope is dispatched. */\n readonly onQuarantine?: (windowId: string, napplet: string) => void;\n /** Visibility for a window the pipeline has not been told about yet. */\n readonly getVisibility?: (windowId: string) => WindowVisibility;\n /** Called when a window becomes visible; kernl releases the port envelopes kehto held for it here. */\n readonly onRelease?: (windowId: string) => void;\n}\n\n/** What the pipeline decided about a message. `unrouted` means no registered window sent it. */\nexport type PipelineDisposition = GuardDisposition | 'unrouted';\n\n/** A message held back until its window is visible or its budget refills. */\ninterface Pending {\n readonly event: MessageEvent;\n readonly napplet: string;\n readonly envelope: GuardEnvelope;\n readonly forward: (event: MessageEvent) => void;\n}\n\n/** The composed guard the shell puts in front of kehto's bridge. */\nexport interface GuardPipeline {\n readonly config: GuardConfig;\n readonly profile$: Observable<GuardProfile>;\n /** Rebuild every layer for a profile. Held messages are dropped; counters restart. */\n setProfile(profile: GuardProfile): void;\n /**\n * Admit, hold or drop one window-level message. Messages from unregistered\n * windows are forwarded so the bridge can report them as unrouted.\n */\n handleWindowMessage(event: MessageEvent, resolveWindow: (event: MessageEvent) => WindowResolution | null, forward: (event: MessageEvent) => void): PipelineDisposition;\n /**\n * Decide one envelope that arrived over a bound port, for kehto's\n * `filterNappletMessage`. `defer` holds every non-control envelope from a\n * window that is not visible (reason `hidden:<class>`) until it is visible\n * again, up to `deferQueue` envelopes. `drop` discards an envelope over its\n * size cap, a burst above the per-second rate, a request over the\n * focus-aware firewall's budget, a hidden window's envelope past the defer\n * queue, and the envelope that triggers a quarantine. Control envelopes are\n * dispatched unless the window is quarantined.\n */\n observe(windowId: string, napplet: string, message: unknown): NappletMessageDecision;\n setVisibility(windowId: string, visibility: WindowVisibility): void;\n getVisibility(windowId: string): WindowVisibility;\n /** Lift quarantine after the user chose to. */\n release(windowId: string): void;\n isQuarantined(windowId: string): boolean;\n /** Drop every queue and counter for a window. */\n forget(windowId: string): void;\n /** Forward what the budget and visibility now allow. */\n drainAll(windowId: string): void;\n}\n\ninterface Layers {\n ingress: IngressGuard;\n gate: VisibilityGate;\n firewall: FocusFirewall;\n}\n\nfunction toEnvelope(data: unknown): GuardEnvelope {\n const record = typeof data === 'object' && data !== null ? (data as Record<string, unknown>) : {};\n const event = typeof record.event === 'object' && record.event !== null ? (record.event as Record<string, unknown>) : {};\n const envelope: GuardEnvelope = {\n type: typeof record.type === 'string' ? record.type : 'unknown',\n size: estimateEnvelopeSize(data),\n };\n return typeof event.kind === 'number' ? { ...envelope, kind: event.kind } : envelope;\n}\n\n/** One envelope that arrived over a bound port, with the visibility the shell reported for its window. */\ninterface PortEnvelope {\n readonly windowId: string;\n readonly napplet: string;\n readonly envelope: GuardEnvelope;\n readonly visibility: WindowVisibility;\n}\n\n/** How the pipeline holds a hidden window's port envelope: counted against `deferQueue`, reported, and left with kehto. */\ntype HoldPort = (port: PortEnvelope, opClass: OpClass) => NappletMessageDecision;\n\n/**\n * What the pipeline answers for a port envelope once the ingress guard has\n * admitted it. Control envelopes are dispatched; a hidden window's other\n * envelopes are held; the rest go to the firewall.\n */\nfunction judgePort(port: PortEnvelope, admitted: GuardDisposition, firewall: FocusFirewall, hold: HoldPort): NappletMessageDecision {\n const { windowId, napplet, envelope, visibility } = port;\n if (admitted === 'quarantine') return 'drop';\n const opClass = classifyEnvelope(envelope);\n if (opClass === 'control') {\n if (admitted === 'pass') firewall.observe(windowId, napplet, envelope, visibility);\n return 'dispatch';\n }\n if (admitted !== 'pass') return 'drop';\n if (!visibility.visible) return hold(port, opClass);\n return firewall.observe(windowId, napplet, envelope, visibility).decision === 'pass' ? 'dispatch' : 'drop';\n}\n\n/**\n * Compose the guard: ingress flood control, then the visibility gate, then the\n * focus-aware firewall, then kehto's bridge.\n *\n * What is enforced where (D-020): kehto binds NAP traffic to a `MessagePort`\n * the bridge owns. Window-level messages, of which only `napplet.hello` is\n * legitimate, are held or dropped by `handleWindowMessage`. Port traffic\n * reaches `observe` through kehto's `filterNappletMessage`, whose answer\n * kehto follows: dispatch, hold until `releaseDeferred`, or drop. Hidden\n * windows' envelopes are held and `onRelease` is called when the window is\n * visible again. Quarantine revokes the window inside the filter, and kehto\n * discards what it held. The runtime firewall configured by\n * `applyRuntimeFirewallRules` adds the profile's per-class rates to every\n * envelope it dispatches, held ones included.\n *\n * @param options - Configuration, clock, event sink and quarantine callback.\n * @returns The pipeline.\n * @example\n * ```ts\n * const pipeline = createGuardPipeline({ config: createGuardConfig('strict'), onEvent: (e) => log.push(e) });\n * window.addEventListener('message', (event) => pipeline.handleWindowMessage(event, resolve, bridge.handleMessage));\n * ```\n */\nexport function createGuardPipeline(options: GuardPipelineOptions): GuardPipeline {\n let config = options.config;\n const profile$ = new BehaviorSubject<GuardProfile>(config.profile);\n const clock = options.now ?? Date.now;\n const known = new Map<string, WindowVisibility>();\n const heldByIngress = new Map<string, Pending[]>();\n const heldByGate = new Map<string, Pending[]>();\n const layerOptions = () => ({\n config,\n ...(options.now ? { now: options.now } : {}),\n ...(options.onEvent ? { onEvent: options.onEvent } : {}),\n });\n // The gate only asks for the applet while `defer` runs, which always follows `admit`.\n let deferring = '';\n const buildLayers = (): Layers => ({\n ingress: createIngressGuard(layerOptions()),\n gate: createVisibilityGate({ ...layerOptions(), nappletFor: () => deferring }),\n firewall: createFocusFirewall(layerOptions()),\n });\n let layers = buildLayers();\n\n function visibilityOf(windowId: string): WindowVisibility {\n if (!known.has(windowId) && options.getVisibility) {\n const visibility = options.getVisibility(windowId);\n known.set(windowId, visibility);\n layers.gate.setVisibility(windowId, visibility);\n }\n return layers.gate.getVisibility(windowId);\n }\n\n function push(queue: Map<string, Pending[]>, windowId: string, pending: Pending): void {\n const list = queue.get(windowId) ?? [];\n list.push(pending);\n queue.set(windowId, list);\n }\n\n function take(queue: Map<string, Pending[]>, windowId: string, count: number): Pending[] {\n const list = queue.get(windowId) ?? [];\n return list.splice(0, count);\n }\n\n function pastGate(windowId: string, pending: Pending): GuardDisposition {\n const opClass = classifyEnvelope(pending.envelope);\n if (layers.gate.shouldDefer(windowId, opClass)) {\n deferring = pending.napplet;\n if (!layers.gate.defer(windowId, pending.envelope)) return 'reject';\n push(heldByGate, windowId, pending);\n return 'defer';\n }\n return pastFirewall(windowId, pending);\n }\n\n function pastFirewall(windowId: string, pending: Pending): GuardDisposition {\n const result = layers.firewall.observe(windowId, pending.napplet, pending.envelope, visibilityOf(windowId));\n if (result.decision !== 'pass') return 'reject';\n pending.forward(pending.event);\n return 'pass';\n }\n\n function admit(windowId: string, napplet: string, envelope: GuardEnvelope, admitOptions?: AdmitOptions): GuardDisposition {\n const disposition = layers.ingress.admit(windowId, napplet, envelope, visibilityOf(windowId), admitOptions);\n if (disposition === 'quarantine') options.onQuarantine?.(windowId, napplet);\n return disposition;\n }\n\n function holdPort(port: PortEnvelope, opClass: OpClass): NappletMessageDecision {\n const { windowId, napplet } = port;\n deferring = napplet;\n if (!layers.gate.defer(windowId, port.envelope)) return 'drop';\n options.onEvent?.({ disposition: 'defer', windowId, napplet, opClass, reason: `hidden:${opClass}`, at: clock() });\n return 'defer';\n }\n\n function drainAll(windowId: string): void {\n const released = layers.ingress.drain(windowId).length;\n for (const pending of take(heldByIngress, windowId, released)) pastGate(windowId, pending);\n const visible = layers.gate.drain(windowId).length;\n for (const pending of take(heldByGate, windowId, visible)) pastFirewall(windowId, pending);\n }\n\n return {\n get config() {\n return config;\n },\n profile$,\n setProfile(profile) {\n config = createGuardConfig(profile);\n layers = buildLayers();\n heldByIngress.clear();\n heldByGate.clear();\n for (const [windowId, visibility] of known) layers.gate.setVisibility(windowId, visibility);\n profile$.next(profile);\n },\n handleWindowMessage(event, resolveWindow, forward) {\n const resolved = resolveWindow(event);\n if (!resolved) {\n forward(event);\n return 'unrouted';\n }\n const { windowId, napplet } = resolved;\n const pending: Pending = { event, napplet, envelope: toEnvelope(event.data), forward };\n const disposition = admit(windowId, napplet, pending.envelope);\n if (disposition === 'defer') push(heldByIngress, windowId, pending);\n return disposition === 'pass' ? pastGate(windowId, pending) : disposition;\n },\n observe(windowId, napplet, message) {\n const envelope = toEnvelope(message);\n const port: PortEnvelope = { windowId, napplet, envelope, visibility: visibilityOf(windowId) };\n return judgePort(port, admit(windowId, napplet, envelope, { hold: false }), layers.firewall, holdPort);\n },\n setVisibility(windowId, visibility) {\n known.set(windowId, visibility);\n layers.gate.setVisibility(windowId, visibility);\n if (!visibility.visible) return;\n drainAll(windowId);\n options.onRelease?.(windowId);\n },\n getVisibility: visibilityOf,\n release: (windowId) => layers.ingress.release(windowId),\n isQuarantined: (windowId) => layers.ingress.isQuarantined(windowId),\n forget(windowId) {\n layers.ingress.forget(windowId);\n layers.gate.forget(windowId);\n layers.firewall.forget(windowId);\n heldByIngress.delete(windowId);\n heldByGate.delete(windowId);\n known.delete(windowId);\n },\n drainAll,\n };\n}\n","import type { FirewallEvent, FirewallPersistence, FirewallStateContainer } from '@kehto/runtime';\nimport type { NappletRules, RateLimit } from '@kehto/firewall';\nimport { applyNappletRules, type GuardConfig, type GuardEvent, type OpClass } from '@kernlize/guard';\nimport type { StorageLike } from '../types.js';\n\n/*\n * Every call kernl makes into the runtime firewall's own configuration lives in\n * this module. kehto/web#336 replaces these seams on hosts that configure\n * permissions (`permissions.setRateLimit`, `onRateLimit`), so moving there is a\n * change to this file only (D-020).\n */\n\n/**\n * Where kernl stores the runtime firewall's configuration in the host storage.\n *\n * @example\n * ```ts\n * localStorage.getItem(RUNTIME_FIREWALL_STORAGE_KEY); // the serialised kehto firewall config\n * ```\n */\nexport const RUNTIME_FIREWALL_STORAGE_KEY = 'kernl:firewall:v1';\n\n/**\n * How the guard's operation classes appear inside kehto's runtime firewall.\n *\n * The runtime keys its observations by the sender capability a message needs\n * (`relay:write`, `resource:fetch`), while the guard classifies by what the\n * message does (`relay:publish`, `resource:bytes`). `null` means the class has\n * no runtime counterpart: deletions share `relay:write` with other publishes,\n * `control` envelopes need no capability, and `generic` becomes the per-applet\n * global rate.\n *\n * @example\n * ```ts\n * RUNTIME_OP_CLASSES['relay:publish']; // 'relay:write'\n * RUNTIME_OP_CLASSES.control; // null\n * ```\n */\nexport const RUNTIME_OP_CLASSES: Readonly<Record<OpClass, string | null>> = Object.freeze({\n 'relay:subscribe': 'relay:read',\n 'relay:publish': 'relay:write',\n 'relay:publish:delete': null,\n 'outbox:subscribe': 'outbox:read',\n 'outbox:publish': 'outbox:write',\n 'resource:bytes': 'resource:fetch',\n 'storage:write': 'state:write',\n 'dm:send': 'dm:write',\n 'intent:invoke': 'intent:write',\n control: null,\n generic: null,\n});\n\n/** One rate limit in the runtime's vocabulary. */\nexport interface RuntimeRateRule {\n readonly opClass: string;\n readonly limit: RateLimit;\n}\n\n/** The rules {@link applyRuntimeFirewallRules} installs for one applet. */\nexport interface RuntimeFirewallRules {\n readonly rates: readonly RuntimeRateRule[];\n readonly globalRate: RateLimit;\n}\n\n/**\n * Translate the guard profile's per-class rates for one applet into the\n * runtime firewall's `(napplet, opClass)` rate limits.\n *\n * @param config - Current guard configuration.\n * @param napplet - Applet identity (dTag).\n * @returns Runtime rate rules and the global fallback rate.\n * @example\n * ```ts\n * runtimeFirewallRules(createGuardConfig('strict'), 'chat').rates.find((r) => r.opClass === 'relay:write');\n * ```\n */\nexport function runtimeFirewallRules(config: GuardConfig, napplet: string): RuntimeFirewallRules {\n // applyNappletRules always registers the applet, so the entry exists.\n const rules = applyNappletRules(config, napplet).firewall.napplets[napplet] as NappletRules;\n const rates: RuntimeRateRule[] = [];\n for (const [opClass, limit] of Object.entries(rules.rateLimits)) {\n const runtimeClass = RUNTIME_OP_CLASSES[opClass as OpClass];\n if (runtimeClass) rates.push({ opClass: runtimeClass, limit });\n }\n return { rates, globalRate: rules.globalRate as RateLimit };\n}\n\n/** The runtime firewall's state, as far as kernl configures it. */\nexport type RuntimeFirewallState = Pick<FirewallStateContainer, 'setRateLimit' | 'setGlobalRate' | 'setUnfocusedMultiplier' | 'setBurstGuard' | 'persist'>;\n\n/**\n * Install the guard profile's rates for an applet in the runtime firewall.\n *\n * The runtime's firewall runs before every dispatch, including the envelopes\n * kernl held for a hidden window and released later, so the profile's limits\n * are pushed into it when a window mounts and again when the profile changes.\n * No policy is set: kehto's `allow` policy bypasses every rate, matcher and\n * burst check, and the user's choices to deny or block live in the grants\n * layer, not here.\n *\n * @param firewallState - `bridge.runtime.firewallState`.\n * @param config - Current guard configuration.\n * @param napplet - Applet identity (dTag).\n * @returns Nothing; the firewall state is mutated and persisted.\n * @example\n * ```ts\n * applyRuntimeFirewallRules(bridge.runtime.firewallState, guardConfig, summary.identity.dTag);\n * ```\n */\nexport function applyRuntimeFirewallRules(firewallState: RuntimeFirewallState, config: GuardConfig, napplet: string): void {\n const rules = runtimeFirewallRules(config, napplet);\n for (const rule of rules.rates) firewallState.setRateLimit(napplet, rule.opClass, rule.limit);\n firewallState.setGlobalRate(napplet, rules.globalRate);\n firewallState.persist();\n}\n\n/**\n * Apply a profile's shell-wide limits to the runtime firewall: the unfocused\n * multiplier, which the runtime applies with the focus kernl reports through\n * `getFocusContext`, and the startup burst guard.\n *\n * @param firewallState - `bridge.runtime.firewallState`.\n * @param config - The guard configuration of the profile now in force.\n * @returns Nothing; the firewall state is mutated and persisted.\n * @example\n * ```ts\n * applyRuntimeFirewallProfile(bridge.runtime.firewallState, createGuardConfig('balanced'));\n * bridge.runtime.firewallState.getConfig().unfocusedMultiplier; // 0.5\n * ```\n */\nexport function applyRuntimeFirewallProfile(firewallState: RuntimeFirewallState, config: GuardConfig): void {\n firewallState.setUnfocusedMultiplier(config.firewall.unfocusedMultiplier);\n firewallState.setBurstGuard(config.firewall.burstGuard);\n firewallState.persist();\n}\n\nconst GUARD_OP_CLASSES: ReadonlyMap<string, OpClass> = new Map(\n Object.entries(RUNTIME_OP_CLASSES).flatMap(([opClass, runtimeClass]) => (runtimeClass ? [[runtimeClass, opClass as OpClass] as const] : [])),\n);\n\n/**\n * Turn a runtime firewall event into a guard event. The runtime's event\n * carries the applet's message; the guard event never does, so nothing the\n * applet sent reaches the guard log. Reasons follow the guard's vocabulary:\n * a rate is `rate:<class>`, the startup burst is `flood:startup`, anything\n * else is `runtime:<ruleId>`.\n *\n * @param event - What the runtime firewall reported.\n * @param at - When it happened.\n * @returns The guard event.\n * @example\n * ```ts\n * toGuardEvent({ windowId: 'w1', napplet: 'chat', opClass: 'state:write', decision: 'reject', action: 'block', ruleId: 'rate:opclass', reason: '…' }, 0).reason;\n * // 'rate:storage:write'\n * ```\n */\nexport function toGuardEvent(event: FirewallEvent, at: number): GuardEvent {\n const opClass = GUARD_OP_CLASSES.get(event.opClass) ?? 'generic';\n const reason = event.ruleId === 'burst' ? 'flood:startup' : event.ruleId.startsWith('rate:') ? `rate:${opClass}` : `runtime:${event.ruleId}`;\n const disposition = event.decision === 'pass' ? 'flag' : 'reject';\n return { disposition, windowId: event.windowId, napplet: event.napplet, opClass, reason, at };\n}\n\n/** The runtime firewall hooks kernl hands to `createShellAdapter`. */\nexport interface RuntimeFirewallHooks {\n readonly firewallPersistence: FirewallPersistence;\n readonly onFirewallEvent: (event: FirewallEvent) => void;\n}\n\n/** Options for {@link createRuntimeFirewallHooks}. */\nexport interface RuntimeFirewallHooksOptions {\n /** The host storage; the config is kept under {@link RUNTIME_FIREWALL_STORAGE_KEY}. */\n readonly storage: StorageLike;\n /** Receives every runtime refusal and flag as a guard event. */\n readonly onEvent: (event: GuardEvent) => void;\n readonly now?: () => number;\n}\n\n/**\n * The runtime firewall's persistence and event sink, through kernl's host\n * storage and guard event stream. These report what the runtime itself\n * refused, which is the startup burst and anything over budget when held\n * envelopes are released; what kernl drops before the runtime sees it is\n * reported by kernl's own guard layers.\n *\n * @param options - Host storage, the guard event sink and a clock.\n * @returns `firewallPersistence` and `onFirewallEvent` for the `ShellAdapter`.\n * @example\n * ```ts\n * const hooks = createRuntimeFirewallHooks({ storage: localStorage, onEvent: (event) => log.push(event) });\n * const adapter: ShellAdapter = { ...rest, ...hooks };\n * ```\n */\nexport function createRuntimeFirewallHooks(options: RuntimeFirewallHooksOptions): RuntimeFirewallHooks {\n const now = options.now ?? Date.now;\n return {\n firewallPersistence: {\n persist: (data) => options.storage.setItem(RUNTIME_FIREWALL_STORAGE_KEY, data),\n load: () => options.storage.getItem(RUNTIME_FIREWALL_STORAGE_KEY),\n },\n onFirewallEvent: (event) => options.onEvent(toGuardEvent(event, now())),\n };\n}\n","import type { Capability } from '@kehto/runtime';\n\n/**\n * Which kehto capabilities a NAP domain needs, following `resolveCapabilitiesNap`.\n * `shell` and `inc` map to nothing: the handshake needs no grant and `inc`\n * reuses the relay capabilities of the messages it carries.\n *\n * @example\n * ```ts\n * DOMAIN_CAPABILITIES.relay; // ['relay:read', 'relay:write']\n * DOMAIN_CAPABILITIES.shell; // []\n * ```\n */\nexport const DOMAIN_CAPABILITIES: Readonly<Record<string, readonly Capability[]>> = Object.freeze({\n shell: [],\n inc: [],\n relay: ['relay:read', 'relay:write'],\n identity: ['identity:read'],\n storage: ['state:read', 'state:write'],\n theme: ['theme:read'],\n keys: ['keys:bind', 'keys:forward'],\n media: ['media:control'],\n notify: ['notify:send', 'notify:channel'],\n config: ['config:read'],\n resource: ['resource:fetch'],\n cvm: ['cvm:call'],\n outbox: ['outbox:read', 'outbox:write'],\n upload: ['upload:write'],\n intent: ['intent:read', 'intent:write'],\n dm: ['dm:read', 'dm:write'],\n fs: ['fs:read', 'fs:write'],\n llm: ['llm:generate'],\n cache: ['cache:read', 'cache:write'],\n});\n\n/**\n * Domains every applet gets without asking: the handshake, in-shell messaging,\n * the theme and scoped storage. No network, and not the identity: which\n * account is signed in is the user's to reveal, so an applet learns it only\n * after the user grants \"your account\" (SOUL opinion 2).\n *\n * @example\n * ```ts\n * BASELINE_DOMAINS.includes('identity'); // false: the account is the user's to reveal\n * capabilitiesForDomains(BASELINE_DOMAINS); // the capabilities granted without asking\n * ```\n */\nexport const BASELINE_DOMAINS: readonly string[] = Object.freeze(['shell', 'inc', 'theme', 'storage']);\n\n/**\n * Capabilities a domain needs. Unknown domains need none, which keeps the\n * grants layer honest about domains kehto adds later: they are advertised only\n * when the environment resolver allows them.\n *\n * @param domain - Bare NAP domain name.\n * @returns The capabilities, possibly empty.\n * @example\n * ```ts\n * capabilitiesForDomain('relay'); // ['relay:read', 'relay:write']\n * ```\n */\nexport function capabilitiesForDomain(domain: string): readonly Capability[] {\n return DOMAIN_CAPABILITIES[domain] ?? [];\n}\n\n/**\n * The union of capabilities a set of domains needs, deduplicated.\n *\n * @param domains - Bare NAP domain names.\n * @returns The capabilities in table order.\n * @example\n * ```ts\n * capabilitiesForDomains(['identity', 'storage']); // ['identity:read', 'state:read', 'state:write']\n * ```\n */\nexport function capabilitiesForDomains(domains: readonly string[]): readonly Capability[] {\n const wanted = new Set(domains);\n const result: Capability[] = [];\n for (const [domain, capabilities] of Object.entries(DOMAIN_CAPABILITIES)) {\n if (wanted.has(domain)) result.push(...capabilities);\n }\n return result;\n}\n","import { Subject } from 'rxjs';\nimport type { AclStateContainer, Capability } from '@kehto/runtime';\nimport type { CapabilityHooks } from '@kehto/shell';\nimport type { AppletIdentity, GrantRecord, Grants, StorageLike } from '../types.js';\nimport { createNamespacedStore } from '../persistence/store.js';\nimport { BASELINE_DOMAINS, capabilitiesForDomains } from './domain-capabilities.js';\n\nconst STORAGE_KEY = 'grants:v1';\n\ninterface StoredGrant {\n readonly dTag: string;\n readonly hash: string;\n readonly domains: readonly string[];\n readonly blocked: boolean;\n}\n\n/** Options for {@link createGrants}. */\nexport interface GrantsOptions {\n /** `bridge.runtime.aclState`; the live source of truth the runtime enforces. */\n readonly acl: AclStateContainer;\n readonly storage: StorageLike;\n /** Domains the shell can offer at all, from `buildShellCapabilities`. */\n readonly availableDomains: () => readonly string[];\n}\n\n/** The grants surface plus the hook the shell calls when an applet is about to run. */\nexport interface KernlGrants extends Grants {\n /** Write this applet's record into the runtime ACL before it runs; returns the record. */\n ensure(identity: AppletIdentity): GrantRecord;\n}\n\nfunction keyOf(identity: AppletIdentity): string {\n return `${identity.dTag}:${identity.hash}`;\n}\n\n/**\n * User-facing grants over kehto's ACL state.\n *\n * The runtime ACL is restrictive (`aclDefaultPolicy`, D-020): an applet with\n * no entry holds nothing. kernl grants the baseline domains plus what the user\n * allowed, and revokes whatever the applet's entry holds beyond that, which\n * covers a domain the user took back and an entry kept from an earlier\n * posture. The per-identity record is persisted at `kernl:grants:v1`; the ACL\n * itself is persisted by kehto. Blocking an applet blocks it in the ACL and empties its\n * environment through {@link createEnvironmentResolver}.\n *\n * @param options - ACL container, storage and the live domain list.\n * @returns The grants surface.\n * @example\n * ```ts\n * const grants = createGrants({ acl: bridge.runtime.aclState, storage, availableDomains });\n * grants.allowDomain(identity, 'relay');\n * grants.get(identity)?.capabilities; // includes 'relay:read' and 'relay:write'\n * ```\n */\nexport function createGrants(options: GrantsOptions): KernlGrants {\n const store = createNamespacedStore(options.storage, 'kernl');\n const records = new Map<string, StoredGrant>(Object.entries(store.getJson<Record<string, StoredGrant>>(STORAGE_KEY, {})));\n const changes$ = new Subject<GrantRecord>();\n\n const persist = (): void => store.setJson(STORAGE_KEY, Object.fromEntries(records));\n\n function stored(identity: AppletIdentity): StoredGrant {\n return records.get(keyOf(identity)) ?? { dTag: identity.dTag, hash: identity.hash, domains: [], blocked: false };\n }\n\n function record(entry: StoredGrant): GrantRecord {\n return {\n identity: { dTag: entry.dTag, hash: entry.hash },\n domains: Object.freeze([...entry.domains]),\n capabilities: capabilitiesForDomains([...BASELINE_DOMAINS, ...entry.domains]),\n blocked: entry.blocked,\n stateQuotaBytes: options.acl.getStateQuota('', entry.dTag, entry.hash),\n };\n }\n\n function syncAcl(entry: StoredGrant): void {\n const wanted = new Set<Capability>(capabilitiesForDomains([...BASELINE_DOMAINS, ...entry.domains]));\n const held = options.acl.getEntry('', entry.dTag, entry.hash)?.capabilities ?? [];\n for (const capability of held) if (!wanted.has(capability)) options.acl.revoke('', entry.dTag, entry.hash, capability);\n for (const capability of wanted) options.acl.grant('', entry.dTag, entry.hash, capability);\n if (entry.blocked) options.acl.block('', entry.dTag, entry.hash);\n else options.acl.unblock('', entry.dTag, entry.hash);\n options.acl.persist();\n }\n\n function commit(entry: StoredGrant): GrantRecord {\n records.set(`${entry.dTag}:${entry.hash}`, entry);\n persist();\n syncAcl(entry);\n const result = record(entry);\n changes$.next(result);\n return result;\n }\n\n function setDomains(identity: AppletIdentity, domains: readonly string[]): void {\n commit({ ...stored(identity), domains: [...domains] });\n }\n\n return {\n list: () => [...records.values()].map(record),\n get: (identity) => {\n const entry = records.get(keyOf(identity));\n return entry ? record(entry) : undefined;\n },\n ensure: (identity) => commit(stored(identity)),\n allowDomain(identity, domain) {\n if (!options.availableDomains().includes(domain)) throw new Error('invalid:domain');\n const current = stored(identity).domains;\n if (!BASELINE_DOMAINS.includes(domain) && !current.includes(domain)) setDomains(identity, [...current, domain]);\n },\n revokeDomain(identity, domain) {\n if (BASELINE_DOMAINS.includes(domain)) throw new Error('denied:baseline-domain');\n const current = stored(identity).domains;\n if (current.includes(domain)) setDomains(identity, current.filter((entry) => entry !== domain));\n },\n block: (identity) => void commit({ ...stored(identity), blocked: true }),\n unblock: (identity) => void commit({ ...stored(identity), blocked: false }),\n setStateQuota(identity, bytes) {\n options.acl.setStateQuota('', identity.dTag, identity.hash, bytes);\n commit(stored(identity));\n },\n availableDomains: () => options.availableDomains(),\n baselineDomains: () => BASELINE_DOMAINS,\n changes$,\n };\n}\n\n/**\n * The `capabilities.resolveEnvironment` hook for the `ShellAdapter`.\n *\n * Each applet sees the baseline domains plus the domains the user allowed,\n * intersected with what the shell offers live. kehto intersects again with\n * its own availability set, so this hook can only narrow. A blocked applet\n * sees only `shell`, enough to finish the handshake and nothing more.\n *\n * @param grants - The grants surface the hook reads.\n * @returns The hook, ready for `adapter.capabilities.resolveEnvironment`.\n * @example\n * ```ts\n * const adapter: ShellAdapter = { ..., capabilities: { resolveEnvironment: createEnvironmentResolver(grants) } };\n * ```\n */\nexport function createEnvironmentResolver(grants: Grants): NonNullable<CapabilityHooks['resolveEnvironment']> {\n return (identity, available) => {\n const record = grants.get({ dTag: identity.dTag, hash: identity.aggregateHash });\n const allowed = new Set(record?.blocked ? ['shell'] : [...grants.baselineDomains(), ...(record?.domains ?? [])]);\n return Object.freeze({\n domains: Object.freeze(available.domains.filter((domain) => allowed.has(domain))),\n services: Object.freeze(available.services.filter((service) => allowed.has(service))),\n });\n };\n}\n","import { getInboxes, getOutboxes, isReplaceable } from 'applesauce-core/helpers';\nimport type { NostrEvent } from '@napplet/core';\nimport type { AppletIdentity, ConsentLine, ConsentSummary } from '../types.js';\n\nconst PROFILE_FIELDS: readonly (readonly [key: string, label: string])[] = [\n ['name', 'Name'],\n ['display_name', 'Display name'],\n ['about', 'About'],\n ['picture', 'Picture'],\n ['banner', 'Banner'],\n ['nip05', 'Verified address'],\n ['lud16', 'Payment address'],\n ['website', 'Website'],\n];\n\nconst KIND_LABELS: Readonly<Record<number, string>> = {\n 1: 'post',\n 4: 'legacy private message',\n 6: 'repost',\n 7: 'reaction',\n 1059: 'sealed message',\n 1111: 'comment',\n 9735: 'payment receipt',\n 30023: 'article',\n};\n\n/** Content preview length for routine publishes. */\nconst PREVIEW_LENGTH = 140;\n/** Hex prefix shown for ids and keys. */\nconst PREFIX_LENGTH = 8;\n/** How many ids a line names before counting the rest. */\nconst NAMED_ITEMS = 3;\n\n/**\n * Shorten a hex id or key to a recognisable prefix.\n *\n * @param hex - A 64-hex id or public key.\n * @returns The first eight characters and an ellipsis.\n * @example\n * ```ts\n * abbreviate('3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d'); // '3bf0c63f…'\n * ```\n */\nexport function abbreviate(hex: string): string {\n return `${hex.slice(0, PREFIX_LENGTH)}…`;\n}\n\nfunction tagValues(event: NostrEvent | undefined, name: string): string[] {\n return (event?.tags ?? []).filter((tag) => tag[0] === name && typeof tag[1] === 'string').map((tag) => tag[1] as string);\n}\n\nconst HEX_KEY = /^[0-9a-f]{64}$/i;\nconst SERVER_ADDRESS = /^wss?:\\/\\//i;\nconst SERVER_TAGS = new Set(['r', 'relay', 'relays']);\nconst TYPE_TAGS = new Set(['k', 'kind']);\n\n/** A server address as the user knows it: no scheme, no trailing slash, no leading `relay.` or `nostr.` label while the rest still names a domain. */\nfunction serverName(address: string): string {\n return address.replace(SERVER_ADDRESS, '').replace(/\\/+$/, '').replace(/^(?:relay|nostr)\\.(?=[^/]*\\.)/i, '');\n}\n\nfunction recordNoun(kind: number | string): string {\n return KIND_LABELS[Number(kind)] ?? `record (type ${kind})`;\n}\n\nfunction coordinate(address: string): string {\n const [kind = '', pubkey = '', identifier = ''] = address.split(':');\n const named = identifier ? ` \"${identifier}\"` : '';\n return `${recordNoun(kind)}${named} by person ${abbreviate(pubkey)}`;\n}\n\nfunction entryLabel(name: string, value: string): string {\n if (name === 'p') return `person ${abbreviate(value)}`;\n if (name === 'e') return `item ${abbreviate(value)}`;\n if (name === 'a') return coordinate(value);\n if (name === 't') return `topic ${value}`;\n if (TYPE_TAGS.has(name)) return `type ${value}`;\n if (SERVER_TAGS.has(name) || SERVER_ADDRESS.test(value)) return `server ${serverName(value)}`;\n // A bare key is named for what it is; an unfamiliar tag name could be protocol vocabulary.\n if (HEX_KEY.test(value)) return `key ${abbreviate(value)}`;\n return `${name} ${value}`;\n}\n\nfunction listItems(event: NostrEvent | undefined): string[] {\n return (event?.tags ?? [])\n .filter((tag) => tag[0] !== 'd' && tag[0] !== 'title' && tag[0] !== 'description' && typeof tag[1] === 'string')\n .map((tag) => entryLabel(tag[0] as string, tag[1] as string));\n}\n\nfunction diff(before: readonly string[], after: readonly string[]): { added: string[]; removed: string[] } {\n const was = new Set(before);\n const now = new Set(after);\n return { added: after.filter((item) => !was.has(item)), removed: before.filter((item) => !now.has(item)) };\n}\n\nfunction describeItems(items: readonly string[], render: (item: string) => string): string {\n const named = items.slice(0, NAMED_ITEMS).map(render).join(', ');\n const rest = items.length - NAMED_ITEMS;\n return rest > 0 ? `${named} and ${rest} more` : named;\n}\n\nfunction changeLines(before: readonly string[], after: readonly string[], noun: string, render: (item: string) => string): ConsentLine[] {\n const { added, removed } = diff(before, after);\n const lines: ConsentLine[] = [];\n if (added.length > 0) lines.push({ label: `${noun} added`, after: `${added.length}: ${describeItems(added, render)}` });\n if (removed.length > 0) lines.push({ label: `${noun} removed`, before: `${removed.length}: ${describeItems(removed, render)}` });\n if (lines.length === 0) lines.push({ label: 'Change', after: 'No entries change' });\n return lines;\n}\n\nfunction parseProfile(event: NostrEvent | undefined): Record<string, unknown> {\n if (!event) return {};\n try {\n const parsed: unknown = JSON.parse(event.content);\n return typeof parsed === 'object' && parsed !== null ? (parsed as Record<string, unknown>) : {};\n } catch {\n return {};\n }\n}\n\nfunction text(value: unknown): string | undefined {\n return typeof value === 'string' && value !== '' ? value : undefined;\n}\n\nfunction profileLines(event: NostrEvent, before: NostrEvent | undefined): ConsentLine[] {\n const was = parseProfile(before);\n const now = parseProfile(event);\n const lines: ConsentLine[] = [];\n for (const [key, label] of PROFILE_FIELDS) {\n const previous = text(was[key]);\n const next = text(now[key]);\n if (previous === next) continue;\n const line: { label: string; before?: string; after?: string } = { label };\n if (previous !== undefined) line.before = previous;\n if (next !== undefined) line.after = next;\n lines.push(line);\n }\n if (lines.length === 0) lines.push({ label: 'Change', after: 'No profile fields change' });\n return lines;\n}\n\nconst MAILBOX_HELP: ConsentLine = { label: 'What this is', after: 'Your inbox is where people send things to you; your outbox is where your posts are kept and found.' };\n\n/**\n * A relay list (NIP-65) as the two lists a person knows: where they are reached\n * and where they publish. An unmarked entry is both and appears in each.\n */\nfunction mailboxLines(event: NostrEvent, before: NostrEvent | undefined): ConsentLine[] {\n const names = (urls: string[]): string[] => urls.map(serverName);\n const inbox = changeLines(names(before ? getInboxes(before) : []), names(getInboxes(event)), 'Inbox', (item) => item);\n const outbox = changeLines(names(before ? getOutboxes(before) : []), names(getOutboxes(event)), 'Outbox', (item) => item);\n const changed = [...inbox, ...outbox].filter((line) => line.label !== 'Change');\n return [MAILBOX_HELP, ...(changed.length > 0 ? changed : [{ label: 'Change', after: 'No entries change' }])];\n}\n\nfunction isListKind(kind: number): boolean {\n return (kind >= 10000 && kind <= 10099) || (kind >= 30000 && kind <= 30099);\n}\n\n/** Deletion request: erases the events and addresses it names. */\nconst DELETION = 5;\n/** Request to vanish: asks services to erase everything the account published. */\nconst VANISH = 62;\n/** The `relay` tag value a request to vanish uses to address every service. */\nconst ALL_SERVICES = 'ALL_RELAYS';\n\n/**\n * Whether {@link describeChange} rates a kind `destructive`: every replaceable\n * and addressable kind (signing one overwrites the version before it),\n * deletions, and requests to vanish.\n *\n * @param kind - The kind of the event about to be signed.\n * @returns True when signing it replaces or erases part of the account's public record.\n * @example\n * ```ts\n * isDestructiveKind(0); // true\n * isDestructiveKind(30311); // true\n * isDestructiveKind(1); // false\n * ```\n */\nexport function isDestructiveKind(kind: number): boolean {\n return isReplaceable(kind) || kind === DELETION || kind === VANISH;\n}\n\nfunction nameOf(event: NostrEvent): string | undefined {\n return tagValues(event, 'title')[0] ?? tagValues(event, 'd')[0];\n}\n\nfunction listTitle(event: NostrEvent): string {\n const name = nameOf(event);\n return name ? `Change the list \"${name}\"` : 'Change a list';\n}\n\nfunction replaceTitle(event: NostrEvent): string {\n const name = nameOf(event);\n // Every labelled kind is either not replaceable or falls in the list range, so only the type is known here.\n const label = `Replace one of your records (type ${event.kind})`;\n return name ? `${label} \"${name}\"` : label;\n}\n\nfunction recordLines(event: NostrEvent, before: NostrEvent | undefined): ConsentLine[] {\n const lines = changeLines(listItems(before), listItems(event), 'Entries', (item) => item);\n if (before !== undefined && before.content !== event.content) lines.push({ label: 'Content', after: 'Replaced' });\n return lines;\n}\n\nfunction deletion(event: NostrEvent, applet: AppletIdentity): ConsentSummary {\n const lines: ConsentLine[] = [\n ...tagValues(event, 'e').map((id) => ({ label: 'Delete', before: abbreviate(id) })),\n ...tagValues(event, 'a').map((address) => ({ label: 'Delete every version of', before: coordinate(address) })),\n ];\n // A deletion names posts only when its `k` tags say every target is one.\n const kinds = tagValues(event, 'k');\n const posts = tagValues(event, 'a').length === 0 && kinds.length > 0 && kinds.every((kind) => kind === '1');\n const noun = `${posts ? 'post' : 'item'}${lines.length === 1 ? '' : 's'}`;\n return destructive(event, applet, `Delete ${lines.length} ${noun}`, lines);\n}\n\nfunction vanish(event: NostrEvent, applet: AppletIdentity): ConsentSummary {\n const services = tagValues(event, 'relay');\n const everywhere = services.length === 0 || services.includes(ALL_SERVICES);\n const lines: ConsentLine[] = [{ label: 'Erase', before: 'Everything this account has published' }];\n lines.push({ label: 'Services asked', after: everywhere ? 'Every service' : describeItems(services, serverName) });\n return destructive(event, applet, 'Ask services to erase your account', lines);\n}\n\n/** The user's preferred applets for an archetype; an applet writing it could route other applets' requests to itself. */\nconst HANDLER_PREFERENCES = 31129;\n\n/** An applet named the way the user can recognise it: its name and publisher, or a pinned version's id. */\nfunction appletName(ref: string): string {\n const [, pubkey = '', name = ''] = ref.split(':');\n if (HEX_KEY.test(ref)) return `pinned applet ${abbreviate(ref)}`;\n return name ? `applet \"${name}\" by person ${abbreviate(pubkey)}` : `applet by person ${abbreviate(pubkey)}`;\n}\n\nfunction handlerEntries(event: NostrEvent | undefined): string[] {\n return (event?.tags ?? [])\n .filter((tag) => (tag[0] === 'a' || tag[0] === 'e' || tag[0] === 'i') && typeof tag[1] === 'string')\n .map((tag) => (tag[0] === 'i' ? `${appletName(tag[2] ?? '')} for \"${(tag[1] as string).replace(/^napplet:/, '')}\"` : appletName(tag[1] as string)));\n}\n\nfunction handlerPreferences(event: NostrEvent, before: NostrEvent | undefined, applet: AppletIdentity): ConsentSummary {\n const archetype = tagValues(event, 'd')[0] ?? 'some requests';\n const lines = changeLines(handlerEntries(before), handlerEntries(event), 'Applets', (entry) => entry);\n if (before !== undefined && before.content !== event.content) lines.push({ label: 'Private choices', after: 'Replaced' });\n return destructive(event, applet, `Change which applets open \"${archetype}\" for you`, lines);\n}\n\nfunction preview(content: string): string {\n const flat = content.replace(/\\s+/g, ' ').trim();\n return flat.length > PREVIEW_LENGTH ? `${flat.slice(0, PREVIEW_LENGTH)}…` : flat;\n}\n\nfunction destructive(event: NostrEvent, applet: AppletIdentity, title: string, lines: ConsentLine[]): ConsentSummary {\n return { title, severity: 'destructive', lines, applet, event };\n}\n\n/**\n * Describe a write the shell is asked to sign as what it changes.\n *\n * Profiles diff field by field; follow, connection and list changes count\n * what was added and removed and name the first few entries in plain words\n * (a person by key prefix, a server by its name); any other\n * replaceable or addressable record diffs its tags and says when its content\n * is replaced, without copying it; deletions list the events and addresses\n * that disappear; a request to vanish names the services asked; a change to\n * the user's preferred applets names the archetype and the applets added and\n * removed, because an applet that wrote it could route other applets'\n * requests to itself. Those kinds\n * are `destructive` because they replace or erase the account's public record. Everything else is `routine` and shows\n * a content preview. Nothing here is protocol vocabulary the user has to know,\n * and nothing secret is copied out of the event; the event itself rides along\n * unchanged for the record view.\n *\n * @param event - The event to be signed.\n * @param before - The current version of the replaceable event, when known.\n * @param applet - The applet asking.\n * @returns The summary the host renders.\n * @example\n * ```ts\n * describeChange(kind3Event, currentFollows, identity).lines[0];\n * // { label: 'Follows added', after: '1: 3bf0c63f…' }\n * ```\n */\nexport function describeChange(event: NostrEvent, before: NostrEvent | undefined, applet: AppletIdentity): ConsentSummary {\n switch (event.kind) {\n case 0:\n return destructive(event, applet, 'Update your profile', profileLines(event, before));\n case 3:\n return destructive(event, applet, 'Change who you follow', changeLines(tagValues(before, 'p'), tagValues(event, 'p'), 'Follows', abbreviate));\n case DELETION:\n return deletion(event, applet);\n case VANISH:\n return vanish(event, applet);\n case HANDLER_PREFERENCES:\n return handlerPreferences(event, before, applet);\n case 10002:\n return destructive(event, applet, 'Change your inbox and outbox', mailboxLines(event, before));\n default:\n if (isListKind(event.kind)) {\n return destructive(event, applet, listTitle(event), changeLines(listItems(before), listItems(event), 'Entries', (item) => item));\n }\n if (isReplaceable(event.kind)) return destructive(event, applet, replaceTitle(event), recordLines(event, before));\n return {\n title: `Publish a ${recordNoun(event.kind)}`,\n severity: 'routine',\n lines: [{ label: 'Content', after: preview(event.content) }],\n applet,\n event,\n };\n }\n}\n","import { catchError, EMPTY, lastValueFrom, takeUntil, timer, toArray } from 'rxjs';\nimport type { EventStore } from 'applesauce-core';\nimport { isAddressableKind, isReplaceable } from 'applesauce-core/helpers';\nimport type { AddressPointerLoader } from 'applesauce-loaders/loaders';\nimport type { ConsentRequest } from '@kehto/runtime';\nimport type { EventTemplate, NostrEvent } from '@napplet/core';\nimport type { AppletIdentity, ConsentLine, ConsentSummary, KernlHost } from '../types.js';\nimport { describeChange, isDestructiveKind } from './describe-change.js';\n\n/** Finds the current version of a replaceable event so the summary can show a diff; undefined when it cannot be found. */\nexport type LookupBefore = (kind: number, pubkey: string, identifier?: string) => Promise<NostrEvent | undefined>;\n\n/** Maps a window to the verified applet running in it. */\nexport type ResolveAppletIdentity = (windowId: string) => AppletIdentity | undefined;\n\n/**\n * How long a consent prompt waits for the network to return the current version, in milliseconds.\n *\n * @example\n * ```ts\n * const lookup = lookupReplaceable(eventStore, { loader, relays: () => tiers.super, timeoutMs: CURRENT_VERSION_TIMEOUT_MS / 2 });\n * ```\n */\nexport const CURRENT_VERSION_TIMEOUT_MS = 4000;\n\n/**\n * The line a destructive summary carries when the version it replaces could not be loaded.\n *\n * @example\n * ```ts\n * summary.lines[0] === UNKNOWN_CURRENT_VERSION; // true when the replaced version could not be loaded\n * UNKNOWN_CURRENT_VERSION.label; // 'Current version'\n * ```\n */\nexport const UNKNOWN_CURRENT_VERSION: ConsentLine = { label: 'Current version', after: 'could not be loaded; this replaces it entirely' };\n\n/** Options for {@link lookupReplaceable}. */\nexport interface LookupReplaceableOptions {\n /** Loads the current version from the network when the store has none. Without it the lookup reads the store only. */\n readonly loader?: AddressPointerLoader;\n /** The relays to ask, read each time a lookup runs. */\n readonly relays?: () => readonly string[];\n /** How long to wait for the loader; defaults to {@link CURRENT_VERSION_TIMEOUT_MS}. */\n readonly timeoutMs?: number;\n}\n\nfunction newest(events: readonly NostrEvent[]): NostrEvent | undefined {\n return events.reduce<NostrEvent | undefined>((best, event) => (!best || event.created_at > best.created_at ? event : best), undefined);\n}\n\n/**\n * A {@link LookupBefore} over the shell's event store and, on a miss, the\n * network.\n *\n * The store answers first. When it holds no version, the applesauce address\n * loader asks the given relays and the lookup waits at most `timeoutMs` for\n * an answer, then takes the newest version that arrived. A loader that fails\n * or stays silent yields undefined, which the consent summary reports as a\n * current version that could not be loaded.\n *\n * @param store - The event store that holds the current replaceable events.\n * @param options - Network loader, relays and timeout.\n * @returns A lookup for {@link createConsentHandler} and {@link createSigningConsent}.\n * @example\n * ```ts\n * const lookupBefore = lookupReplaceable(eventStore, { loader, relays: () => tiers.get().discovery });\n * createConsentHandler(host, lookupBefore, resolveApplet);\n * ```\n */\nexport function lookupReplaceable(store: Pick<EventStore, 'getReplaceable'>, options: LookupReplaceableOptions = {}): LookupBefore {\n const { loader } = options;\n return async (kind, pubkey, identifier) => {\n const cached = store.getReplaceable(kind, pubkey, identifier);\n if (cached || !loader) return cached;\n const pointer = { kind, pubkey, relays: [...(options.relays?.() ?? [])], ...(identifier === undefined ? {} : { identifier }) };\n const loaded = await lastValueFrom(\n loader(pointer).pipe(takeUntil(timer(options.timeoutMs ?? CURRENT_VERSION_TIMEOUT_MS)), catchError(() => EMPTY), toArray()),\n );\n return newest(loaded);\n };\n}\n\nfunction identifierOf(event: NostrEvent): string | undefined {\n if (!isAddressableKind(event.kind)) return undefined;\n const tag = event.tags.find((entry) => entry[0] === 'd');\n return tag?.[1] ?? '';\n}\n\n/**\n * Describe a write against the version it replaces. A replaceable or\n * addressable write whose current version cannot be found stays destructive\n * and says so first, rather than reading as a first version that removes\n * nothing.\n */\nasync function describeAgainstCurrent(event: NostrEvent, lookupBefore: LookupBefore, applet: AppletIdentity): Promise<ConsentSummary> {\n if (!isReplaceable(event.kind)) return describeChange(event, undefined, applet);\n const before = await lookupBefore(event.kind, event.pubkey, identifierOf(event));\n const summary = describeChange(event, before, applet);\n return before ? summary : { ...summary, lines: [UNKNOWN_CURRENT_VERSION, ...summary.lines] };\n}\n\n/**\n * Answer kehto's own consent requests.\n *\n * The kehto runtime kernl pins emits only `firewall-policy` requests, which\n * carry no event; kernl's guard decides firewall policy itself, so those are\n * refused without asking. Destructive writes are not asked for here: kehto\n * signs through `ShellAdapter.auth.getSigner`, and kernl gates that seam with\n * {@link createSigningConsent}. A request that does carry an event, from a\n * window the shell recognises, is still described and put to the user, so a\n * kehto release that adds such prompts is answered honestly; one from a\n * window the shell cannot name is refused.\n *\n * @param host - Supplies `presentConsent`.\n * @param lookupBefore - Finds the current replaceable event for the diff.\n * @param resolveApplet - Maps the requesting window to its applet identity.\n * @returns A handler for `bridge.registerConsentHandler`.\n * @example\n * ```ts\n * bridge.registerConsentHandler(createConsentHandler(host, lookupBefore, (windowId) => applets.get(windowId)?.summary.identity));\n * ```\n */\nexport function createConsentHandler(\n host: Pick<KernlHost, 'presentConsent'>,\n lookupBefore: LookupBefore,\n resolveApplet: ResolveAppletIdentity,\n): (request: ConsentRequest) => void {\n return (request) => {\n const applet = resolveApplet(request.windowId);\n const { event } = request;\n if (!event || !applet) {\n request.resolve(false);\n return;\n }\n void describeAgainstCurrent(event, lookupBefore, applet).then((summary) =>\n host.presentConsent({ summary, resolve: (allowed) => request.resolve(allowed) }),\n );\n };\n}\n\n/** The event fields the signing gate reads, as an applet supplied them. */\nexport type SigningTemplate = Readonly<Partial<EventTemplate>>;\n\n/**\n * Resolves when an applet's write may be signed and rejects with a stable\n * reason when it may not: `denied:consent` when the user refuses,\n * `denied:unknown-applet` for a destructive write from a window the shell did\n * not mount, `denied:signed-out` for a destructive write while nobody is\n * signed in, `invalid:event-kind` when the kind is not a number.\n */\nexport type SigningConsent = (windowId: string, template: SigningTemplate) => Promise<void>;\n\n/** What {@link createSigningConsent} needs from the shell. */\nexport interface SigningConsentOptions {\n readonly host: Pick<KernlHost, 'presentConsent'>;\n readonly lookupBefore: LookupBefore;\n readonly resolveApplet: ResolveAppletIdentity;\n /** The account that will sign, for the before lookup; undefined while nobody is signed in. */\n readonly pubkey: () => string | undefined;\n}\n\nfunction draftOf(template: SigningTemplate, kind: number, pubkey: string): NostrEvent {\n return {\n id: '',\n sig: '',\n pubkey,\n kind,\n created_at: template.created_at ?? 0,\n tags: Array.isArray(template.tags) ? template.tags : [],\n content: typeof template.content === 'string' ? template.content : '',\n };\n}\n\n/**\n * The consent gate kernl puts in front of every signature it makes for an\n * applet.\n *\n * Routine kinds pass without a prompt. A destructive kind (see\n * {@link isDestructiveKind}) is described against the account's current\n * version, from the event store or the network (see {@link lookupReplaceable}),\n * and put to the user through\n * `host.presentConsent`; the gate waits for the answer and nothing is signed\n * unless it is yes. The summary's `event` is the unsigned draft: its `id` and\n * `sig` are empty because signing has not happened yet.\n *\n * @param options - Host, before lookup, window-to-applet lookup and the signing pubkey.\n * @returns The gate for `createAuthHooks` and the outbox service.\n * @example\n * ```ts\n * const consent = createSigningConsent({ host, lookupBefore: lookupReplaceable(store), resolveApplet, pubkey: () => accounts.active?.pubkey });\n * await consent('applet-1', { kind: 0, content: '{\"name\":\"bob\"}', tags: [] }); // asks the user first\n * ```\n */\nexport function createSigningConsent(options: SigningConsentOptions): SigningConsent {\n return async (windowId, template) => {\n const { kind } = template;\n if (typeof kind !== 'number') throw new Error('invalid:event-kind');\n if (!isDestructiveKind(kind)) return;\n const applet = options.resolveApplet(windowId);\n if (!applet) throw new Error('denied:unknown-applet');\n const pubkey = options.pubkey();\n if (pubkey === undefined) throw new Error('denied:signed-out');\n const summary = await describeAgainstCurrent(draftOf(template, kind, pubkey), options.lookupBefore, applet);\n const allowed = await new Promise<boolean>((resolve) => options.host.presentConsent({ summary, resolve }));\n if (!allowed) throw new Error('denied:consent');\n };\n}\n","import {\n createGroupMessagesProvider,\n createLegacyMessagesProvider,\n createMessagingRegistry,\n createPrivateMessagesProvider,\n createRatchetMessagesProvider,\n type MessagingBackend,\n type MessagingRegistry,\n type MessagingRegistryOptions,\n type ProviderAvailability,\n type ProviderDeps,\n type SavedMessagingPreferences,\n} from '@kernlize/messaging';\nimport type { ISigner } from 'applesauce-signers';\nimport type { MessagingBackendFactories, StorageLike } from '../types.js';\nimport { createNamespacedStore } from '../persistence/store.js';\nimport { MESSAGING_UNAVAILABLE_REASONS, signerAvailability, type MessagingEncryption } from './availability.js';\n\nconst STORAGE_KEY = 'messaging:v1';\n\n/**\n * What is switched on for someone who has never chosen: the two providers that reach anyone with\n * an account, so a first message can be read and answered. The others publish something about\n * the account when they start, so they wait for the user to switch them on (D-016, D-018).\n */\nconst FIRST_RUN: SavedMessagingPreferences = Object.freeze({ enabled: Object.freeze(['private', 'legacy']) });\n\n/** Options for {@link createDefaultMessaging}. */\nexport interface DefaultMessagingOptions {\n readonly storage: StorageLike;\n /** Backend constructors; a provider without one stays unavailable. */\n readonly backends?: MessagingBackendFactories;\n /**\n * The active account's signer, read on every availability check. When given,\n * `private`, `ratchet` and `group` are available only while it has `nip44` and\n * `legacy` only while it has `nip04`, whichever backend is supplied for them.\n */\n readonly signer?: () => ISigner | undefined;\n /** Puts the reply question to the user; see `MessagingRegistryOptions.askReply`. */\n readonly askReply?: MessagingRegistryOptions['askReply'];\n}\n\nconst ENCRYPTION: Readonly<Record<keyof MessagingBackendFactories, MessagingEncryption>> = { private: 'nip44', legacy: 'nip04', ratchet: 'nip44', group: 'nip44' };\n\nfunction availabilityFor(id: keyof MessagingBackendFactories, options: DefaultMessagingOptions): () => ProviderAvailability {\n const factory = options.backends?.[id];\n const { signer } = options;\n if (factory && signer) return () => signerAvailability(signer(), ENCRYPTION[id]);\n if (factory) return () => ({ available: true });\n const reason = id === 'ratchet' || id === 'group' ? MESSAGING_UNAVAILABLE_REASONS.noRuntime : MESSAGING_UNAVAILABLE_REASONS.signInRequired;\n return () => ({ available: false, reason });\n}\n\nfunction depsFor(id: keyof MessagingBackendFactories, options: DefaultMessagingOptions): ProviderDeps {\n const available = availabilityFor(id, options);\n const factory = options.backends?.[id] as () => MessagingBackend;\n return {\n available,\n createBackend(): MessagingBackend {\n const availability = available();\n if (!availability.available) throw new Error(`unavailable:${availability.reason}`);\n return factory();\n },\n };\n}\n\n/**\n * The shell's messaging registry with kernl's four providers registered and\n * preferences persisted at `kernl:messaging:v1`.\n *\n * `createKernl` passes the account-signer backends for all four providers\n * and the active account's signer, so each follows the account:\n * `sign-in-required` while nobody is signed in, `signer-cannot-encrypt` while\n * the signer lacks the encryption the format needs. A provider given no\n * backend stays unavailable: `no-runtime` for `ratchet` and `group`, `sign-in-required`\n * for the others. The shell describes, it does not pretend.\n *\n * The providers start in the order private, legacy, ratchet, group, with\n * `private` and `legacy` switched on for someone who has never chosen; each\n * starts as soon as an account that can run it signs in. The user's own\n * choices, order, reply rule and per-person answers are saved and win.\n *\n * @param options - Storage, backend constructors, the active signer and the reply question.\n * @returns A `MessagingRegistry`.\n * @example\n * ```ts\n * const messaging = createDefaultMessaging({ storage: localStorage });\n * messaging.get('private')?.availability; // { available: false, reason: 'sign-in-required' }\n * messaging.get('ratchet')?.availability; // { available: false, reason: 'no-runtime' }\n * messaging.get('group')?.availability; // { available: false, reason: 'no-runtime' }\n * ```\n */\nexport function createDefaultMessaging(options: DefaultMessagingOptions): MessagingRegistry {\n const store = createNamespacedStore(options.storage, 'kernl');\n const registry = createMessagingRegistry({\n preferences: store.getJson<SavedMessagingPreferences | null>(STORAGE_KEY, null) ?? FIRST_RUN,\n ...(options.askReply ? { askReply: options.askReply } : {}),\n onChange: (next) => store.setJson(STORAGE_KEY, next),\n });\n registry.register(createPrivateMessagesProvider(depsFor('private', options)));\n registry.register(createLegacyMessagesProvider(depsFor('legacy', options)));\n registry.register(createRatchetMessagesProvider(depsFor('ratchet', options)));\n registry.register(createGroupMessagesProvider(depsFor('group', options)));\n return registry;\n}\n","import type { IAccount } from 'applesauce-accounts';\nimport type { ISigner } from 'applesauce-signers';\nimport type { ProviderAvailability } from '@kernlize/messaging';\nimport { isReadOnlyAccount } from '../applesauce/auth-hooks.js';\n\n/**\n * The encryption a messaging backend needs from the account signer.\n *\n * @example\n * ```ts\n * const method: MessagingEncryption = 'nip44';\n * ```\n */\nexport type MessagingEncryption = 'nip44' | 'nip04';\n\n/**\n * The reasons kernl gives for a provider that cannot run. Every provider\n * reports the first two, which follow the active account; `noRuntime` is\n * reported only by a `ratchet` or `group` provider a host registered without a backend.\n *\n * @example\n * ```ts\n * MESSAGING_UNAVAILABLE_REASONS.signInRequired; // 'sign-in-required'\n * Object.values(MESSAGING_UNAVAILABLE_REASONS); // ['sign-in-required', 'signer-cannot-encrypt', 'no-runtime']\n * ```\n */\nexport const MESSAGING_UNAVAILABLE_REASONS: Readonly<Record<'signInRequired' | 'signerCannotEncrypt' | 'noRuntime', string>> = Object.freeze({\n signInRequired: 'sign-in-required',\n signerCannotEncrypt: 'signer-cannot-encrypt',\n noRuntime: 'no-runtime',\n});\n\n/**\n * Whether a signer can carry messages that need `method`.\n *\n * @param signer - The active account's signer, or `undefined` while nobody is signed in.\n * @param method - The encryption the provider uses.\n * @returns Available, or unavailable with `sign-in-required` or `signer-cannot-encrypt`.\n * @example\n * ```ts\n * signerAvailability(undefined, 'nip44'); // { available: false, reason: 'sign-in-required' }\n * signerAvailability(new PrivateKeySigner(), 'nip44'); // { available: true }\n * ```\n */\nexport function signerAvailability(signer: ISigner | undefined, method: MessagingEncryption): ProviderAvailability {\n if (!signer) return { available: false, reason: MESSAGING_UNAVAILABLE_REASONS.signInRequired };\n return signer[method] ? { available: true } : { available: false, reason: MESSAGING_UNAVAILABLE_REASONS.signerCannotEncrypt };\n}\n\n/**\n * The signer messaging may use for an account. A read-only account is signed\n * in but can neither sign nor decrypt, so it is offered without its\n * encryption methods and reports `signer-cannot-encrypt`.\n *\n * @param account - The active account, if any.\n * @returns The account itself, a signer without encryption for a read-only account, or `undefined`.\n * @example\n * ```ts\n * const signer = () => messagingSigner(accounts.active);\n * signerAvailability(signer(), 'nip44');\n * ```\n */\nexport function messagingSigner(account: IAccount | undefined): ISigner | undefined {\n if (!account || !isReadOnlyAccount(account)) return account;\n return { getPublicKey: () => account.getPublicKey(), signEvent: (template) => account.signEvent(template) };\n}\n","import { kinds, verifyEvent, type NostrEvent } from 'applesauce-core/helpers';\nimport { lockGiftWrap, unlockGiftWrap } from 'applesauce-common/helpers/gift-wrap';\nimport { getConversationParticipants } from 'applesauce-common/helpers/messages';\nimport { sealRumor, toRumor } from 'applesauce-common/operations/gift-wrap';\nimport { PrivateKeySigner } from 'applesauce-signers';\nimport type { MessagingBackend } from '@kernlize/messaging';\nimport { createSignerBackend, type MessageFormat, type OpenedMessage, type SignerMessagingOptions } from './signer-backend.js';\n\n/** NIP-59 lets wraps carry a timestamp up to two days old so arrival times do not date the message. */\nconst WRAP_JITTER_SECONDS = 2 * 24 * 60 * 60;\n\n/**\n * Wrap a seal for one recipient under a key that exists for this wrap only.\n * The key is generated inside an applesauce `PrivateKeySigner` and goes out of\n * scope when the wrap is signed; it is never stored (SOUL opinion 1).\n */\nasync function wrapForRecipient(recipient: string, seal: NostrEvent, createdAt: number): Promise<NostrEvent> {\n const ephemeral = new PrivateKeySigner();\n const content = await ephemeral.nip44.encrypt(recipient, JSON.stringify(seal));\n const jitter = Math.floor(Math.random() * WRAP_JITTER_SECONDS);\n return ephemeral.signEvent({ kind: kinds.GiftWrap, created_at: createdAt - jitter, tags: [['p', recipient]], content });\n}\n\nasync function openWrap(event: NostrEvent, self: string, signer: Parameters<MessageFormat['open']>[2]): Promise<OpenedMessage | undefined> {\n const addressed = event.tags.some((tag) => tag[0] === 'p' && tag[1] === self);\n if (event.kind !== kinds.GiftWrap || !addressed || !verifyEvent(event)) return undefined;\n const rumor = await unlockGiftWrap(event, signer);\n lockGiftWrap(event);\n if (rumor.kind !== kinds.PrivateDirectMessage) return undefined;\n return { id: rumor.id, senderPubkey: rumor.pubkey, participants: getConversationParticipants(rumor), createdAt: rumor.created_at, content: rumor.content };\n}\n\n/**\n * The private message format: a kind 14 rumour sealed in a kind 13 event the\n * account signs, wrapped in a kind 1059 event signed by a one-time key.\n *\n * @example\n * ```ts\n * createSignerBackend(options, PRIVATE_MESSAGE_FORMAT);\n * ```\n */\nexport const PRIVATE_MESSAGE_FORMAT: MessageFormat = {\n implementation: 'nip17',\n encryption: 'nip44',\n filters: (self) => [{ kinds: [kinds.GiftWrap], '#p': [self] }],\n open: openWrap,\n async seal({ signer, self, others, content, createdAt, inboxRelays }) {\n // The rumour is built by hand: applesauce's text-content operation tags anyone mentioned in the text,\n // which would add them to the conversation on the reader's side.\n const rumor = await toRumor(signer)({ kind: kinds.PrivateDirectMessage, created_at: createdAt, content, tags: others.map((pubkey) => ['p', pubkey]) });\n const targets = [...others, self];\n const relays = await Promise.all(targets.map((target) => inboxRelays(target)));\n const outgoing = [];\n for (const [index, target] of targets.entries()) {\n const seal = await sealRumor(target, signer)(rumor);\n outgoing.push({ event: await wrapForRecipient(target, seal, createdAt), relays: relays[index] as string[] });\n }\n return { id: rumor.id, outgoing };\n },\n};\n\n/**\n * A `MessagingBackend` for private messages (NIP-17) over the active account's\n * signer.\n *\n * Sending builds a kind 14 rumour, seals it once per recipient and once for\n * the user in a kind 13 event signed by `signer()` and encrypted with its\n * `nip44`, and wraps each seal in a kind 1059 event signed by an ephemeral key\n * that lives only inside an applesauce `PrivateKeySigner` for that one wrap.\n * Each wrap goes to its recipient's kind 10050 inbox relays, or to the\n * `outbox` and `super` tiers when they publish none. Receiving subscribes to\n * kind 1059 events tagged with the user on the user's own inbox relays and\n * opens them with applesauce's gift-wrap helpers and the same signer; a wrap\n * that does not open, or holds anything but a kind 14 rumour, is ignored.\n *\n * Conversation ids are the sorted participant set, the user included, so both\n * sides of a conversation use the same id. Message ids are the rumour id, so\n * the copy addressed to the user is not filed twice.\n *\n * @param options - Store, pool, tiers, and the active account's signer and public key.\n * @returns A backend for the `private` provider; available while the signer has `nip44`.\n * @example\n * ```ts\n * const backend = createPrivateMessagesBackend({\n * store: kernl.eventStore,\n * pool: kernl.pool,\n * tiers: kernl.relays,\n * signer: () => kernl.accounts.active,\n * selfPubkey: () => kernl.accounts.active?.pubkey,\n * });\n * await backend.send({ recipients: [alice], content: 'hello' });\n * ```\n */\nexport function createPrivateMessagesBackend(options: SignerMessagingOptions): MessagingBackend {\n return createSignerBackend(options, PRIVATE_MESSAGE_FORMAT);\n}\n","import type { Observable } from 'rxjs';\nimport type { EventStore } from 'applesauce-core';\nimport { isHexKey, unixNow, type NostrEvent } from 'applesauce-core/helpers';\nimport { getConversationParticipants } from 'applesauce-common/helpers/messages';\nimport type { ISigner } from 'applesauce-signers';\nimport type { DmMessage, DmSendRequest, DmStatus, NostrFilter } from '@napplet/core';\nimport type { MessagingBackend } from '@kernlize/messaging';\nimport type { RelayTiers } from '../types.js';\nimport { subscribeWithEose, type ApplesaucePool, type EoseSubscription } from '../applesauce/relay-hooks.js';\nimport { createReplaceableLoader } from '../applesauce/identity-providers.js';\nimport { signerAvailability, type MessagingEncryption } from './availability.js';\nimport { conversationIdOf, createConversationStore } from './conversation-store.js';\nimport { createInboxRelays, type InboxRelays } from './inbox-relays.js';\n\n/**\n * What a signer-backed messaging backend needs from the shell. `signer` and\n * `selfPubkey` are read on every call, so one backend follows the active account.\n *\n * @example\n * ```ts\n * const options: SignerMessagingOptions = {\n * store: kernl.eventStore,\n * pool: kernl.pool,\n * tiers: kernl.relays,\n * signer: () => kernl.accounts.active,\n * selfPubkey: () => kernl.accounts.active?.pubkey,\n * };\n * ```\n */\nexport interface SignerMessagingOptions {\n /** The shell's event store; inbox relay lists are read from it. */\n readonly store: EventStore;\n readonly pool: ApplesaucePool;\n readonly tiers: RelayTiers;\n /** The active account's signer, read on every call. The only key holder the backend uses. */\n readonly signer: () => ISigner | undefined;\n /** The active account's public key, read on every call. */\n readonly selfPubkey: () => string | undefined;\n /** Clock in Unix seconds. Defaults to the wall clock. */\n readonly now?: () => number;\n /** Emits when the active account changes, so the inbox follows it without waiting for the next call. */\n readonly accountChanges?: Observable<unknown>;\n}\n\n/** A message read out of an event, before it is filed. */\nexport interface OpenedMessage {\n readonly id: string;\n readonly senderPubkey: string;\n /** Everyone the message names, sender included. */\n readonly participants: readonly string[];\n readonly createdAt: number;\n readonly content: string;\n}\n\n/** What a sealed message publishes: each event and the relays it goes to. */\nexport interface SealedMessage {\n readonly id: string;\n readonly outgoing: readonly { readonly event: NostrEvent; readonly relays: readonly string[] }[];\n}\n\n/** Everything a format needs to seal one message. */\nexport interface SealRequest {\n readonly signer: ISigner;\n readonly self: string;\n readonly others: readonly string[];\n readonly content: string;\n readonly createdAt: number;\n readonly inboxRelays: InboxRelays;\n}\n\n/** One message format: how to ask for, open and seal its events. */\nexport interface MessageFormat {\n readonly implementation: string;\n readonly encryption: MessagingEncryption;\n filters(self: string): NostrFilter[];\n /** Read an event addressed to or written by `self`; `undefined` for anything that does not open. */\n open(event: NostrEvent, self: string, signer: ISigner): Promise<OpenedMessage | undefined>;\n seal(request: SealRequest): Promise<SealedMessage>;\n}\n\ninterface Subscriber {\n readonly conversationId?: string;\n readonly onMessage: (message: DmMessage) => void;\n}\n\ninterface Inbox {\n readonly pubkey: string;\n ready: Promise<void>;\n handle?: EoseSubscription;\n}\n\ninterface Session {\n readonly signer: ISigner;\n readonly self: string;\n}\n\nconst CAPABILITIES = ['send', 'receive', 'subscribe', 'history'];\n\n/** The people a send goes to, other than `self`; refuses an unknown conversation, nobody, or a key that is not hex. */\nexport function recipientsOf(request: DmSendRequest, self: string): string[] {\n const named = request.conversationId === undefined ? request.recipients : getConversationParticipants(request.conversationId);\n if (request.conversationId !== undefined && !named.includes(self)) throw new Error('invalid:unknown-conversation');\n const others = [...new Set(named)].filter((pubkey) => pubkey !== self);\n if (others.length === 0) throw new Error('invalid:no-recipients');\n if (!others.every((pubkey) => isHexKey(pubkey))) throw new Error('invalid:recipient');\n return others;\n}\n\nasync function publishAll(pool: ApplesaucePool, sealed: SealedMessage): Promise<void> {\n for (const { event, relays } of sealed.outgoing) {\n const results = await pool.publish([...relays], event).catch(() => []);\n if (!results.some((result) => result.ok)) throw new Error('unavailable:offline');\n }\n}\n\n/**\n * A `MessagingBackend` for one message format, over the active account's\n * signer. The backend keeps one inbox subscription for the active account and\n * files what it can open into an in-memory store; when the account changes or\n * signs out, the subscription closes and the store is cleared, so one\n * account's messages are never shown to another.\n *\n * Reads wait for events that already arrived to be opened. A send files the\n * message as `sent` before publishing it and takes it back out if no relay\n * accepted it; the copy that later arrives from the user's own inbox carries\n * the same id and is not delivered twice.\n *\n * @param options - Store, pool, tiers, signer and clock.\n * @param format - How the format seals and opens its events.\n * @returns A backend for `createDefaultMessaging`.\n * @example\n * ```ts\n * const backend = createSignerBackend(options, privateMessageFormat);\n * await backend.send({ recipients: [alice], content: 'hi' });\n * ```\n */\nexport function createSignerBackend(options: SignerMessagingOptions, format: MessageFormat): MessagingBackend {\n const now = options.now ?? unixNow;\n const inboxRelays = createInboxRelays(options.store, createReplaceableLoader(options.store, options.pool, options.tiers), options.tiers);\n const store = createConversationStore();\n const subscribers = new Map<string, Subscriber>();\n const pending = new Set<Promise<void>>();\n let inbox: Inbox | undefined;\n let subscriptionCount = 0;\n\n const signerOf = (): ISigner | undefined => (options.selfPubkey() === undefined ? undefined : options.signer());\n const session = (): Session => {\n const signer = signerOf();\n const availability = signerAvailability(signer, format.encryption);\n if (!availability.available) throw new Error(`unavailable:${availability.reason}`);\n return { signer: signer as ISigner, self: options.selfPubkey() as string };\n };\n\n const file = (self: string, opened: OpenedMessage): DmMessage => {\n const participants = [...new Set([self, ...opened.participants])];\n const message: DmMessage = {\n id: opened.id,\n conversationId: conversationIdOf(participants),\n senderPubkey: opened.senderPubkey,\n createdAt: opened.createdAt,\n content: opened.content,\n status: opened.senderPubkey === self ? 'sent' : 'received',\n };\n if (store.owner !== self || !store.add(message, participants)) return message;\n for (const subscriber of subscribers.values()) {\n if (subscriber.conversationId === undefined || subscriber.conversationId === message.conversationId) subscriber.onMessage(message);\n }\n return message;\n };\n\n const ingest = (self: string, signer: ISigner, event: NostrEvent): void => {\n const opening = format.open(event, self, signer).then(\n (opened) => void (opened && file(self, opened)),\n () => undefined,\n );\n pending.add(opening);\n void opening.finally(() => pending.delete(opening));\n };\n\n const closeInbox = (): void => {\n inbox?.handle?.unsubscribe();\n inbox = undefined;\n store.reset();\n };\n\n const openInbox = (current: Session): Promise<void> => {\n store.reset(current.self);\n const entry: Inbox = { pubkey: current.self, ready: Promise.resolve() };\n inbox = entry;\n entry.ready = inboxRelays(current.self).then((relays) => {\n if (inbox !== entry) return;\n entry.handle = subscribeWithEose(options.pool, relays, format.filters(current.self), (item) => {\n if (item !== 'EOSE') ingest(current.self, current.signer, item);\n });\n });\n return entry.ready;\n };\n\n const sync = async (): Promise<void> => {\n if (!signerAvailability(signerOf(), format.encryption).available) closeInbox();\n else if (inbox?.pubkey !== options.selfPubkey()) {\n closeInbox();\n await openInbox(session());\n } else await inbox?.ready;\n await Promise.all(pending);\n };\n\n const changes = options.accountChanges?.subscribe(() => void sync());\n\n return {\n status(): DmStatus {\n const self = options.selfPubkey();\n return {\n available: signerAvailability(signerOf(), format.encryption).available,\n ...(self === undefined ? {} : { ownerPubkey: self }),\n implementations: [format.implementation],\n capabilities: CAPABILITIES,\n };\n },\n async conversations(query) {\n await sync();\n return store.conversations(query);\n },\n async messages(query) {\n await sync();\n return store.messages(query);\n },\n async send(request) {\n const current = session();\n const others = recipientsOf(request, current.self);\n await sync();\n const createdAt = now();\n const sealed = await format.seal({ ...current, others, content: request.content, createdAt, inboxRelays });\n const message = file(current.self, { id: sealed.id, senderPubkey: current.self, participants: others, createdAt, content: request.content });\n try {\n await publishAll(options.pool, sealed);\n } catch (error) {\n store.remove(message.conversationId, message.id);\n throw error;\n }\n return { ok: true, message };\n },\n async subscribe(request, onMessage) {\n await sync();\n subscriptionCount += 1;\n const subscriptionId = `${format.implementation}-${subscriptionCount}`;\n subscribers.set(subscriptionId, { ...(request.conversationId === undefined ? {} : { conversationId: request.conversationId }), onMessage });\n return { subscriptionId };\n },\n unsubscribe(subscriptionId) {\n return { ok: subscribers.delete(subscriptionId) };\n },\n close() {\n changes?.unsubscribe();\n subscribers.clear();\n closeInbox();\n },\n };\n}\n","import type { DmConversation, DmConversationPage, DmConversationQuery, DmMessage, DmMessagePage, DmMessageQuery } from '@napplet/core';\nimport { createConversationIdentifier } from 'applesauce-common/helpers/messages';\n\n/** Decrypted messages for one account, grouped by conversation. Lives in memory only. */\nexport interface ConversationStore {\n /** The account the stored messages belong to. */\n readonly owner: string | undefined;\n /** Forget every message and start over for `owner`. */\n reset(owner?: string): void;\n /** Store a message; `false` when one with the same id is already in its conversation. */\n add(message: DmMessage, participants: readonly string[]): boolean;\n remove(conversationId: string, id: string): void;\n conversations(query?: DmConversationQuery): DmConversationPage;\n messages(query: DmMessageQuery): DmMessagePage;\n}\n\ninterface Thread {\n readonly participants: readonly string[];\n readonly messages: DmMessage[];\n}\n\nconst DEFAULT_CONVERSATION_LIMIT = 50;\nconst DEFAULT_MESSAGE_LIMIT = 100;\n\n/**\n * The conversation id for a set of people: applesauce's identifier, the\n * sorted, deduplicated public keys joined by `:`. Both sides of a\n * conversation compute the same id because it includes the owner.\n *\n * @param participants - Every participant, the owner included.\n * @returns A stable id such as `\"<pubkey a>:<pubkey b>\"`.\n * @example\n * ```ts\n * conversationIdOf(['bb', 'aa', 'bb']); // 'aa:bb'\n * ```\n */\nexport function conversationIdOf(participants: readonly string[]): string {\n return createConversationIdentifier([...participants]);\n}\n\nfunction latest(thread: Thread): number {\n return Math.max(...thread.messages.map((message) => message.createdAt));\n}\n\nfunction page<T>(items: readonly T[], cursor: string | undefined, limit: number): { items: T[]; cursor?: string } {\n const offset = cursor === undefined ? 0 : Number.parseInt(cursor, 10) || 0;\n const slice = items.slice(offset, offset + limit);\n const end = offset + slice.length;\n return { items: slice, ...(end < items.length ? { cursor: String(end) } : {}) };\n}\n\n/**\n * An in-memory store of normalized messages for the account that owns it.\n * Messages are ordered by `createdAt`; a conversation's participants are the\n * people other than the owner, and it is a group when it has more than two\n * people. A conversation whose last message was removed is not listed.\n *\n * @returns An empty store with no owner.\n * @example\n * ```ts\n * const store = createConversationStore();\n * store.reset(me);\n * store.add(message, [me, alice]);\n * store.conversations().conversations[0]?.kind; // 'direct'\n * ```\n */\nexport function createConversationStore(): ConversationStore {\n const threads = new Map<string, Thread>();\n let owner: string | undefined;\n\n const summarize = (id: string, thread: Thread): DmConversation => {\n return {\n id,\n kind: thread.participants.length > 2 ? 'group' : 'direct',\n participants: thread.participants.filter((pubkey) => pubkey !== owner).map((pubkey) => ({ pubkey })),\n unread: thread.messages.filter((message) => message.status === 'received').length,\n updatedAt: latest(thread),\n };\n };\n\n return {\n get owner() {\n return owner;\n },\n reset(next) {\n owner = next;\n threads.clear();\n },\n add(message, participants) {\n const thread = threads.get(message.conversationId) ?? { participants: [...new Set(participants)].sort(), messages: [] };\n if (thread.messages.some((entry) => entry.id === message.id)) return false;\n thread.messages.push(message);\n thread.messages.sort((a, b) => a.createdAt - b.createdAt);\n threads.set(message.conversationId, thread);\n return true;\n },\n remove(conversationId, id) {\n const thread = threads.get(conversationId);\n thread?.messages.splice(thread.messages.findIndex((entry) => entry.id === id), 1);\n },\n conversations(query = {}) {\n const all = [...threads]\n .filter(([, thread]) => thread.messages.length > 0)\n .sort(([, a], [, b]) => latest(b) - latest(a))\n .map(([id, thread]) => summarize(id, thread));\n const result = page(all, query.cursor, query.limit ?? DEFAULT_CONVERSATION_LIMIT);\n return { conversations: result.items, ...(result.cursor === undefined ? {} : { cursor: result.cursor }) };\n },\n messages(query) {\n const all = threads.get(query.conversationId)?.messages ?? [];\n const result = page(all, query.cursor, query.limit ?? DEFAULT_MESSAGE_LIMIT);\n return { messages: result.items, ...(result.cursor === undefined ? {} : { cursor: result.cursor }) };\n },\n };\n}\n","import { lastValueFrom } from 'rxjs';\nimport type { EventStore } from 'applesauce-core';\nimport { kinds, mergeRelaySets, type NostrEvent } from 'applesauce-core/helpers';\nimport { getRelaysFromList } from 'applesauce-common/helpers/lists';\nimport type { AddressPointerLoader } from 'applesauce-loaders/loaders';\nimport type { RelayTiers } from '../types.js';\n\n/**\n * Resolves where a person reads their private messages and invitations.\n *\n * @example\n * ```ts\n * const inboxRelays: InboxRelays = async () => ['wss://inbox.example'];\n * ```\n */\nexport type InboxRelays = (pubkey: string) => Promise<string[]>;\n\n/**\n * Where to deliver to, or read from, a person's message inbox: the relays in\n * their kind 10050 list, loaded through the replaceable loader when the store\n * does not hold it, else the user's `outbox` and `super` tiers. The loader\n * completes empty when its relays fail, so a failed lookup also falls back.\n *\n * @param store - The shell's event store.\n * @param loader - The replaceable loader that fills the store on a miss.\n * @param tiers - Relay tiers; `discovery` is asked for the list, `outbox` and `super` are the fallback.\n * @returns A resolver from public key to relay URLs.\n * @example\n * ```ts\n * const inboxRelays = createInboxRelays(eventStore, loader, tiers);\n * await inboxRelays(pubkey); // ['wss://inbox.example'] or the outbox and super tiers\n * ```\n */\nexport function createInboxRelays(store: EventStore, loader: AddressPointerLoader, tiers: RelayTiers): InboxRelays {\n const load = async (pubkey: string): Promise<NostrEvent | undefined> => {\n const cached = store.getReplaceable(kinds.DirectMessageRelaysList, pubkey);\n if (cached) return cached;\n const pointer = { kind: kinds.DirectMessageRelaysList, pubkey, relays: [...tiers.get().discovery] };\n return lastValueFrom(loader(pointer), { defaultValue: undefined });\n };\n return async (pubkey) => {\n const list = await load(pubkey);\n const relays = list ? getRelaysFromList(list) : [];\n return relays.length > 0 ? relays : mergeRelaySets(tiers.get().outbox, tiers.get().super);\n };\n}\n","import { kinds, mergeRelaySets, verifyEvent, type NostrEvent } from 'applesauce-core/helpers';\nimport { isValidLegacyMessage, unlockLegacyMessage } from 'applesauce-common/helpers/legacy-messages';\nimport { getConversationParticipants } from 'applesauce-common/helpers/messages';\nimport { LegacyMessageFactory } from 'applesauce-common/factories/legacy-message';\nimport type { ISigner } from 'applesauce-signers';\nimport type { MessagingBackend } from '@kernlize/messaging';\nimport { createSignerBackend, type MessageFormat, type OpenedMessage, type SignerMessagingOptions } from './signer-backend.js';\n\nasync function openLegacy(event: NostrEvent, self: string, signer: ISigner): Promise<OpenedMessage | undefined> {\n if (!isValidLegacyMessage(event) || !verifyEvent(event)) return undefined;\n const participants = getConversationParticipants(event);\n if (!participants.includes(self)) return undefined;\n const content = await unlockLegacyMessage(event, self, signer);\n return { id: event.id, senderPubkey: event.pubkey, participants, createdAt: event.created_at, content };\n}\n\n/**\n * The legacy direct-message format: one kind 4 event encrypted with `nip04`,\n * whose author and recipient are public.\n *\n * @example\n * ```ts\n * createSignerBackend(options, LEGACY_MESSAGE_FORMAT);\n * ```\n */\nexport const LEGACY_MESSAGE_FORMAT: MessageFormat = {\n implementation: 'nip04',\n encryption: 'nip04',\n filters: (self) => [\n { kinds: [kinds.EncryptedDirectMessage], '#p': [self] },\n { kinds: [kinds.EncryptedDirectMessage], authors: [self] },\n ],\n open: openLegacy,\n async seal({ signer, self, others, content, createdAt, inboxRelays }) {\n if (others.length > 1) throw new Error('invalid:groups-unsupported');\n const recipient = others[0] as string;\n const event = await LegacyMessageFactory.create(recipient, content).created(createdAt).sign(signer);\n return { id: event.id, outgoing: [{ event, relays: mergeRelaySets(...(await Promise.all([inboxRelays(recipient), inboxRelays(self)]))) }] };\n },\n};\n\n/**\n * A `MessagingBackend` for the legacy direct-message format (NIP-04) over the\n * active account's signer.\n *\n * Sending encrypts the text to the one recipient with `signer().nip04`, signs\n * the kind 4 event with the account and publishes it to the recipient's inbox\n * relays and the user's own, so the user's other devices see it too. Receiving\n * subscribes to kind 4 events addressed to or written by the user and decrypts\n * them with the same signer. Conversation ids and message shapes match\n * {@link createPrivateMessagesBackend}; groups are refused with\n * `invalid:groups-unsupported` because the format has none.\n *\n * @param options - Store, pool, tiers, and the active account's signer and public key.\n * @returns A backend for the `legacy` provider; available while the signer has `nip04`.\n * @example\n * ```ts\n * const backend = createLegacyMessagesBackend({\n * store: kernl.eventStore,\n * pool: kernl.pool,\n * tiers: kernl.relays,\n * signer: () => kernl.accounts.active,\n * selfPubkey: () => kernl.accounts.active?.pubkey,\n * });\n * backend.subscribe({}, (message) => console.log(message.content));\n * ```\n */\nexport function createLegacyMessagesBackend(options: SignerMessagingOptions): MessagingBackend {\n return createSignerBackend(options, LEGACY_MESSAGE_FORMAT);\n}\n","import { verifyEvent, type NostrEvent } from 'applesauce-core/helpers';\nimport type { ISigner } from 'applesauce-signers';\nimport { NdrRuntime, type NdrRuntimeOptions, type Rumor } from 'nostr-double-ratchet';\nimport type { DmMessage, DmSendRequest, DmStatus, NostrFilter } from '@napplet/core';\nimport type { MessagingBackend } from '@kernlize/messaging';\nimport type { StorageLike } from '../types.js';\nimport { subscribeWithEose } from '../applesauce/relay-hooks.js';\nimport { signerAvailability } from './availability.js';\nimport { conversationIdOf, createConversationStore } from './conversation-store.js';\nimport { createSealedRatchetStorage } from './ratchet-storage.js';\nimport type { SignerMessagingOptions } from './signer-backend.js';\n\n/** The library's rumour kind for a chat message; typing notices, receipts and controls use others. */\nconst CHAT_MESSAGE_KIND = 14;\nconst CAPABILITIES = ['send', 'receive', 'subscribe', 'history', 'double-ratchet'];\n\n/**\n * What the ratchet backend needs: the signer backends' options plus the\n * storage the library's sealed state is kept in.\n *\n * @example\n * ```ts\n * const options: RatchetMessagingOptions = { ...signerOptions, storage: localStorage };\n * ```\n */\nexport interface RatchetMessagingOptions extends Omit<SignerMessagingOptions, 'store' | 'now'> {\n /** Where the library's device key and session state are kept, sealed to the account. */\n readonly storage: StorageLike;\n /**\n * How long the library waits for relays to return the account's device\n * list, as `{ fetchMs, fastMs }`. Defaults to the library's 10 s and 2 s.\n */\n readonly discoveryTimeouts?: { readonly fetchMs: number; readonly fastMs: number };\n}\n\ntype Transport = Pick<NdrRuntimeOptions, 'nostrSubscribe' | 'nostrPublish' | 'nostrSign'>;\n\ninterface Account {\n readonly self: string;\n readonly runtime: NdrRuntime;\n readonly ready: Promise<void>;\n readonly detach: () => void;\n /** Set when setup failed, so the next call starts over. */\n failed?: boolean;\n}\n\n/**\n * The library's relay seams over kernl's pool. Ratchet traffic is read from\n * and written to the user's `outbox` and `super` tiers, so both sides must\n * share a relay (D-016). Owner events the library leaves unsigned are signed\n * by the account signer; device and session events arrive already signed by\n * keys the library holds.\n */\nfunction transportFor(options: RatchetMessagingOptions, signer: ISigner): Transport {\n const relays = (): string[] => {\n const tiers = options.tiers.get();\n return [...new Set([...tiers.outbox, ...tiers.super])];\n };\n // The library leaves owner events with an empty `pubkey`; an account signer checks the hash it signs, so only the template goes to it.\n const sign = (event: NostrEvent): Promise<NostrEvent> =>\n typeof event.sig === 'string' ? Promise.resolve(event) : signer.signEvent({ kind: event.kind, created_at: event.created_at, tags: event.tags, content: event.content });\n type Verified = Awaited<ReturnType<NdrRuntimeOptions['nostrPublish']>>;\n return {\n nostrSign: async (event) => (await sign(event as NostrEvent)) as Verified,\n nostrSubscribe(filter, onEvent) {\n const handle = subscribeWithEose(options.pool, relays(), [filter as NostrFilter], (item) => {\n if (item !== 'EOSE' && verifyEvent(item)) onEvent(item as Verified);\n });\n return () => handle.unsubscribe();\n },\n async nostrPublish(event) {\n const signed = await sign(event as NostrEvent);\n const results = await options.pool.publish(relays(), signed).catch(() => []);\n if (!results.some((result) => result.ok)) throw new Error('unavailable:offline');\n return signed as Verified;\n },\n };\n}\n\nfunction recipientOf(request: DmSendRequest, self: string): string {\n const named = request.conversationId === undefined ? request.recipients : request.conversationId.split(':');\n if (request.conversationId !== undefined && !named.includes(self)) throw new Error('invalid:unknown-conversation');\n const others = [...new Set(named)].filter((pubkey) => pubkey !== self);\n if (others.length !== 1) throw new Error(others.length === 0 ? 'invalid:no-recipients' : 'invalid:groups-unsupported');\n return others[0] as string;\n}\n\n/**\n * A `MessagingBackend` for ratchet sessions (nostr-double-ratchet), over the\n * active account's signer.\n *\n * For each signed-in account the backend runs one `NdrRuntime`. The account\n * signer signs the owner's device list; the library generates and holds its\n * own device key and per-session ratchet keys, which never leave it except as\n * ciphertext sealed to the account by {@link createSealedRatchetStorage}.\n * Opening a runtime registers this browser as a device of the account and\n * publishes its invite, so a correspondent can start a session; sessions and\n * keys survive a reload, the conversation list does not (D-016).\n *\n * Only chat messages are filed: typing notices, receipts and controls are\n * dropped. Sessions are one to one, so a send names exactly one other person.\n * When the account changes or signs out the runtime closes and the\n * conversations are cleared.\n *\n * @param options - Pool, tiers, storage and the active account's signer and public key.\n * @returns A backend for the `ratchet` provider; available while the signer has `nip44`.\n * @example\n * ```ts\n * const backend = createRatchetMessagesBackend({\n * pool: kernl.pool,\n * tiers: kernl.relays,\n * storage: localStorage,\n * signer: () => kernl.accounts.active,\n * selfPubkey: () => kernl.accounts.active?.pubkey,\n * });\n * await backend.send({ recipients: [alice], content: 'hello' });\n * ```\n */\nexport function createRatchetMessagesBackend(options: RatchetMessagingOptions): MessagingBackend {\n const timeouts = options.discoveryTimeouts;\n const discovery = timeouts ? { appKeysFetchTimeoutMs: timeouts.fetchMs, appKeysFastTimeoutMs: timeouts.fastMs } : {};\n const store = createConversationStore();\n const subscribers = new Map<string, { conversationId?: string; onMessage(message: DmMessage): void }>();\n let account: Account | undefined;\n let subscriptionCount = 0;\n\n const signerOf = (): ISigner | undefined => (options.selfPubkey() === undefined ? undefined : options.signer());\n const usable = (): boolean => signerAvailability(signerOf(), 'nip44').available;\n\n const file = (self: string, message: DmMessage, participants: readonly string[]): void => {\n if (store.owner !== self || !store.add(message, participants)) return;\n for (const subscriber of subscribers.values()) {\n if (subscriber.conversationId === undefined || subscriber.conversationId === message.conversationId) subscriber.onMessage(message);\n }\n };\n\n const received = (self: string) => (rumor: Rumor, from: string): void => {\n if (rumor.kind !== CHAT_MESSAGE_KIND) return;\n const tagged = rumor.tags.filter((tag) => tag[0] === 'p').map((tag) => tag[1] as string);\n const participants = [...new Set([self, from, ...tagged])];\n const status = from === self ? 'sent' : 'received';\n file(self, { id: rumor.id, conversationId: conversationIdOf(participants), senderPubkey: from, createdAt: rumor.created_at, content: rumor.content, status }, participants);\n };\n\n const close = (): void => {\n account?.detach();\n account?.runtime.close();\n account = undefined;\n store.reset();\n };\n\n const open = (self: string, signer: ISigner): Account => {\n store.reset(self);\n const runtime = new NdrRuntime({\n ...transportFor(options, signer),\n storage: createSealedRatchetStorage({ storage: options.storage, signer, owner: self }),\n ...discovery,\n });\n const detach = runtime.onSessionEvent(received(self));\n const ready = (async () => {\n await runtime.initForOwner(self);\n await runtime.ensureCurrentDeviceRegistered(self);\n await runtime.republishInvite();\n })();\n return { self, runtime, ready, detach };\n };\n\n const sync = async (): Promise<Account | undefined> => {\n if (!usable()) close();\n else if (account?.self !== options.selfPubkey() || account?.failed) {\n close();\n account = open(options.selfPubkey() as string, signerOf() as ISigner);\n }\n const current = account;\n await current?.ready.catch(() => {\n current.failed = true;\n throw new Error('unavailable:offline');\n });\n return current;\n };\n\n const changes = options.accountChanges?.subscribe(() => void sync().catch(() => undefined));\n\n return {\n status(): DmStatus {\n const self = options.selfPubkey();\n return { available: usable(), ...(self === undefined ? {} : { ownerPubkey: self }), implementations: ['ndr'], capabilities: CAPABILITIES };\n },\n async conversations(query) {\n await sync();\n return store.conversations(query);\n },\n async messages(query) {\n await sync();\n return store.messages(query);\n },\n async send(request) {\n const availability = signerAvailability(signerOf(), 'nip44');\n if (!availability.available) throw new Error(`unavailable:${availability.reason}`);\n const self = options.selfPubkey() as string;\n const recipient = recipientOf(request, self);\n const current = (await sync()) as Account;\n const rumor = await current.runtime.sendMessage(recipient, request.content);\n const participants = [self, recipient];\n const message: DmMessage = { id: rumor.id, conversationId: conversationIdOf(participants), senderPubkey: self, createdAt: rumor.created_at, content: request.content, status: 'sent' };\n file(self, message, participants);\n return { ok: true, message };\n },\n async subscribe(request, onMessage) {\n await sync();\n subscriptionCount += 1;\n const subscriptionId = `ndr-${subscriptionCount}`;\n subscribers.set(subscriptionId, { ...(request.conversationId === undefined ? {} : { conversationId: request.conversationId }), onMessage });\n return { subscriptionId };\n },\n unsubscribe(subscriptionId) {\n return { ok: subscribers.delete(subscriptionId) };\n },\n close() {\n changes?.unsubscribe();\n subscribers.clear();\n close();\n },\n };\n}\n","import type { ISigner } from 'applesauce-signers';\nimport type { StorageAdapter } from 'nostr-double-ratchet';\nimport type { StorageLike } from '../types.js';\n\n/** NIP-44 encrypts at most 65535 bytes; a UTF-16 code unit takes at most three UTF-8 bytes, so 16384 units always fit. */\nconst CHUNK_UNITS = 16_384;\n\ninterface SlotIndex {\n next: number;\n slots: Record<string, number>;\n}\n\n/**\n * What {@link createSealedRatchetStorage} needs.\n *\n * @example\n * ```ts\n * const options: SealedRatchetStorageOptions = { storage: localStorage, signer: account, owner: account.pubkey };\n * ```\n */\nexport interface SealedRatchetStorageOptions {\n readonly storage: StorageLike;\n /** The account signer; every value is encrypted to `owner` with its `nip44`. */\n readonly signer: ISigner;\n readonly owner: string;\n}\n\nfunction chunks(text: string): string[] {\n const parts: string[] = [];\n for (let start = 0; start < text.length; start += CHUNK_UNITS) parts.push(text.slice(start, start + CHUNK_UNITS));\n return parts;\n}\n\n/**\n * The ratchet library's storage, sealed to the account. The library keeps its\n * device key and session state here; kernl writes each value only as\n * ciphertext the account signer encrypted to itself with `nip44`, under an\n * opaque slot number, and keeps the map from the library's key names (which\n * name correspondents) to slots in one more sealed entry. Nothing readable\n * reaches `storage`, so the key rule in `SOUL.md` opinion 1 holds for every\n * secret the library generates (D-016).\n *\n * Values are decrypted once and then served from memory, so an extension or\n * remote signer is asked once per value per page load. Writes are applied in\n * order.\n *\n * @param options - Backing storage, the account signer and its public key.\n * @returns A `StorageAdapter` for `NdrRuntime`.\n * @example\n * ```ts\n * const storage = createSealedRatchetStorage({ storage: localStorage, signer: account, owner: account.pubkey });\n * await storage.put('v1/note', { hello: 'world' });\n * await storage.get('v1/note'); // { hello: 'world' }\n * ```\n */\nexport function createSealedRatchetStorage(options: SealedRatchetStorageOptions): StorageAdapter {\n const { storage, owner } = options;\n const nip44 = options.signer.nip44 as NonNullable<ISigner['nip44']>;\n const prefix = `kernl:ratchet:v1:${owner}:`;\n const values = new Map<string, unknown>();\n let writes: Promise<void> = Promise.resolve();\n\n const seal = async (value: unknown): Promise<string> => {\n const parts = await Promise.all(chunks(JSON.stringify(value)).map((part) => nip44.encrypt(owner, part)));\n return JSON.stringify(parts);\n };\n const open = async <T>(raw: string): Promise<T> => {\n const parts = await Promise.all((JSON.parse(raw) as string[]).map((part) => nip44.decrypt(owner, part)));\n return JSON.parse(parts.join('')) as T;\n };\n\n const readIndex = async (): Promise<SlotIndex> => {\n const raw = storage.getItem(`${prefix}index`);\n return raw === null ? { next: 0, slots: {} } : open<SlotIndex>(raw);\n };\n const loading = readIndex();\n const write = (task: (index: SlotIndex) => Promise<void>): Promise<void> => {\n writes = writes.then(async () => task(await loading));\n return writes;\n };\n const saveIndex = async (index: SlotIndex): Promise<void> => storage.setItem(`${prefix}index`, await seal(index));\n\n return {\n async get<T = unknown>(key: string): Promise<T | undefined> {\n if (values.has(key)) return values.get(key) as T;\n const slot = (await loading).slots[key];\n const raw = slot === undefined ? null : storage.getItem(`${prefix}${slot}`);\n if (raw === null) return undefined;\n const value = await open<T>(raw);\n if (!values.has(key)) values.set(key, value);\n return values.get(key) as T;\n },\n put<T = unknown>(key: string, value: T): Promise<void> {\n values.set(key, value);\n return write(async (index) => {\n const known = index.slots[key];\n const slot = known ?? index.next;\n storage.setItem(`${prefix}${slot}`, await seal(value));\n if (known !== undefined) return;\n index.slots[key] = slot;\n index.next = slot + 1;\n await saveIndex(index);\n });\n },\n del(key: string): Promise<void> {\n values.delete(key);\n return write(async (index) => {\n const slot = index.slots[key];\n if (slot === undefined) return;\n storage.removeItem(`${prefix}${slot}`);\n delete index.slots[key];\n await saveIndex(index);\n });\n },\n async list(match = ''): Promise<string[]> {\n await writes;\n return Object.keys((await loading).slots).filter((key) => key.startsWith(match));\n },\n };\n}\n","import { unixNow } from 'applesauce-core/helpers';\nimport type { ISigner } from 'applesauce-signers';\nimport { createApplicationMessageIntent, createChatRumor } from '@internet-privacy/marmot-ts';\nimport type { DmMessage, DmStatus } from '@napplet/core';\nimport type { MessagingBackend } from '@kernlize/messaging';\nimport type { StorageLike } from '../types.js';\nimport { createReplaceableLoader } from '../applesauce/identity-providers.js';\nimport { signerAvailability } from './availability.js';\nimport { createConversationStore } from './conversation-store.js';\nimport { createGroupNetwork } from './group-network.js';\nimport { groupIdOf, membersOf, openGroupSession, type GroupSession, type GroupSessionContext } from './group-session.js';\nimport { createInboxRelays } from './inbox-relays.js';\nimport { recipientsOf, type SignerMessagingOptions } from './signer-backend.js';\n\nconst CAPABILITIES = ['send', 'receive', 'subscribe', 'history'];\n\n/**\n * What the group backend needs: the signer-backend options plus storage for\n * the group library's state, which is sealed to the account before it is\n * written.\n *\n * @example\n * ```ts\n * const options: GroupMessagingOptions = { ...signerOptions, storage: localStorage };\n * ```\n */\nexport interface GroupMessagingOptions extends SignerMessagingOptions {\n readonly storage: StorageLike;\n}\n\ninterface Subscriber {\n readonly conversationId?: string;\n readonly onMessage: (message: DmMessage) => void;\n}\n\n/**\n * A `MessagingBackend` for group sessions (Marmot, MLS over Nostr) over the\n * active account's signer, built on `@internet-privacy/marmot-ts`.\n *\n * The account signer proves who each member is and opens invitations; the\n * group library holds the group secrets, which move on with every commit, and\n * kernl seals everything the library stores to the account with `nip44`\n * (D-018). When an account first uses the backend it publishes a key package\n * (kind 30443) to its inbox relays and `outbox` tier, so others can start a\n * group with it, and publishes a fresh one after each invitation uses it up.\n *\n * A send to people goes to the group with exactly those members, else to a\n * new one that invites each of them by their key package; a recipient with\n * none is refused with `unavailable:recipient-not-ready`. Group events (kind\n * 445) go to the `outbox` and `super` tiers. Invitations arrive as gift wraps\n * on the user's inbox relays and are joined as they open. When the account\n * changes or signs out, the session closes and its messages are forgotten.\n *\n * Conversation ids are the group id in hex. A device is one member, so a\n * second device of the same account sees only groups it was invited to.\n *\n * @param options - Store, pool, tiers, storage, and the active account's signer and public key.\n * @returns A backend for the `group` provider; available while the signer has `nip44`.\n * @example\n * ```ts\n * const backend = createGroupMessagesBackend({\n * store: kernl.eventStore,\n * pool: kernl.pool,\n * tiers: kernl.relays,\n * storage: localStorage,\n * signer: () => kernl.accounts.active,\n * selfPubkey: () => kernl.accounts.active?.pubkey,\n * });\n * await backend.send({ recipients: [alice, bob], content: 'hello both' });\n * ```\n */\nexport function createGroupMessagesBackend(options: GroupMessagingOptions): MessagingBackend {\n const now = options.now ?? unixNow;\n const inboxRelays = createInboxRelays(options.store, createReplaceableLoader(options.store, options.pool, options.tiers), options.tiers);\n const store = createConversationStore();\n const subscribers = new Map<string, Subscriber>();\n const pending = new Set<Promise<unknown>>();\n let session: GroupSession | undefined;\n let subscriptionCount = 0;\n\n const deliver = (owner: string, message: DmMessage, participants: readonly string[]): DmMessage => {\n if (store.owner !== owner || !store.add(message, participants)) return message;\n for (const subscriber of subscribers.values()) {\n if (subscriber.conversationId === undefined || subscriber.conversationId === message.conversationId) subscriber.onMessage(message);\n }\n return message;\n };\n\n const context = (owner: string): GroupSessionContext => ({\n pool: options.pool,\n tiers: options.tiers,\n storage: options.storage,\n network: createGroupNetwork(options.pool, inboxRelays),\n inboxRelays,\n track(work) {\n pending.add(work);\n void work.finally(() => pending.delete(work));\n },\n deliver: (message, participants) => void deliver(owner, message, participants),\n });\n\n const signerOf = (): ISigner | undefined => (options.selfPubkey() === undefined ? undefined : options.signer());\n const close = (): void => {\n session?.close();\n session = undefined;\n store.reset();\n };\n\n const active = (): GroupSession => {\n const signer = signerOf();\n const availability = signerAvailability(signer, 'nip44');\n if (!availability.available) throw new Error(`unavailable:${availability.reason}`);\n const self = options.selfPubkey() as string;\n if (session?.self === self) return session;\n close();\n store.reset(self);\n session = openGroupSession(context(self), self, signer as ISigner);\n return session;\n };\n\n const sync = async (): Promise<void> => {\n if (!signerAvailability(signerOf(), 'nip44').available) return close();\n await active().ready;\n while (pending.size > 0) await Promise.all(pending);\n };\n\n const changes = options.accountChanges?.subscribe(() => void sync());\n\n return {\n status(): DmStatus {\n const self = options.selfPubkey();\n return {\n available: signerAvailability(signerOf(), 'nip44').available,\n ...(self === undefined ? {} : { ownerPubkey: self }),\n implementations: ['marmot'],\n capabilities: CAPABILITIES,\n };\n },\n async conversations(query) {\n await sync();\n return store.conversations(query);\n },\n async messages(query) {\n await sync();\n return store.messages(query);\n },\n async send(request) {\n const live = active();\n const client = await live.ready;\n const group =\n request.conversationId === undefined\n ? await live.groupFor(client, recipientsOf({ recipients: request.recipients, content: request.content }, live.self))\n : live.existing(client, request.conversationId);\n const rumor = createChatRumor({ pubkey: live.self, content: request.content, created_at: now() });\n const sent: DmMessage = { id: rumor.id, conversationId: groupIdOf(group), senderPubkey: live.self, createdAt: rumor.created_at, content: rumor.content, status: 'sent' };\n const message = deliver(live.self, sent, membersOf(group));\n const results = await client.groups.send(group.id, createApplicationMessageIntent(rumor)).catch(() => []);\n if (!results.some((result) => Object.values(result.response).some((response) => response.ok))) {\n store.remove(message.conversationId, message.id);\n throw new Error('unavailable:offline');\n }\n return { ok: true, message };\n },\n async subscribe(request, onMessage) {\n await sync();\n subscriptionCount += 1;\n const subscriptionId = `marmot-${subscriptionCount}`;\n subscribers.set(subscriptionId, { ...(request.conversationId === undefined ? {} : { conversationId: request.conversationId }), onMessage });\n return { subscriptionId };\n },\n unsubscribe(subscriptionId) {\n return { ok: subscribers.delete(subscriptionId) };\n },\n close() {\n changes?.unsubscribe();\n subscribers.clear();\n close();\n },\n };\n}\n","import { lastValueFrom, toArray } from 'rxjs';\nimport type { NostrEvent } from 'applesauce-core/helpers';\nimport type { NostrNetworkInterface, PublishResponse } from '@internet-privacy/marmot-ts';\nimport type { NostrFilter } from '@napplet/core';\nimport { subscribeWithEose, type ApplesaucePool } from '../applesauce/relay-hooks.js';\nimport type { InboxRelays } from './inbox-relays.js';\n\nconst asArray = <T>(value: T | T[]): T[] => (Array.isArray(value) ? value : [value]);\n\n/**\n * The group library's view of the network, over the shell's one relay pool\n * (SOUL opinion 1). A publish no relay took answers with no acknowledgements\n * rather than throwing, so the library records the failure itself; a request\n * that fails answers with no events.\n *\n * @param pool - The shell's relay pool.\n * @param inboxRelays - Where a person reads their invitations.\n * @returns A `NostrNetworkInterface` for `MarmotClient`.\n * @example\n * ```ts\n * const network = createGroupNetwork(kernl.pool, inboxRelays);\n * await network.request(['wss://relay.example'], { kinds: [30443], authors: [alice] });\n * ```\n */\nexport function createGroupNetwork(pool: ApplesaucePool, inboxRelays: InboxRelays): NostrNetworkInterface {\n return {\n async publish(relays, event) {\n const results = await pool.publish(relays, event).catch(() => []);\n return Object.fromEntries(results.map((result): [string, PublishResponse] => [result.from, { from: result.from, ok: result.ok }]));\n },\n request(relays, filters) {\n return lastValueFrom(pool.request(relays, asArray(filters)).pipe(toArray())).catch((): NostrEvent[] => []);\n },\n subscription(relays, filters) {\n return {\n subscribe(observer) {\n return subscribeWithEose(pool, relays, asArray(filters) as NostrFilter[], (item) => {\n if (item !== 'EOSE') observer.next?.(item);\n });\n },\n };\n },\n getUserInboxRelays: inboxRelays,\n };\n}\n","import { bytesToHex, kinds, mergeRelaySets, type NostrEvent } from 'applesauce-core/helpers';\nimport type { ISigner } from 'applesauce-signers';\nimport {\n ADDRESSABLE_KEY_PACKAGE_KIND,\n GROUP_EVENT_KIND,\n MarmotClient,\n deserializeApplicationData,\n getGroupMemberPubkeys,\n type MarmotGroup,\n type NostrNetworkInterface,\n} from '@internet-privacy/marmot-ts';\nimport type { DmMessage } from '@napplet/core';\nimport type { StorageLike, RelayTiers } from '../types.js';\nimport { subscribeWithEose, type ApplesaucePool, type EoseSubscription } from '../applesauce/relay-hooks.js';\nimport { createSealedGroupStore, type SealedGroupStoreOptions } from './group-storage.js';\nimport type { InboxRelays } from './inbox-relays.js';\n\n/** The chat convention the group library suggests for text; anything else carried in a group is not a message. */\nconst CHAT_KIND = 9;\n\n/** Background work that fails leaves the group as it was; the next event or send tries again. */\nconst ignore = (): undefined => undefined;\n\n/** What a group session shares with the backend that opened it. */\nexport interface GroupSessionContext {\n readonly pool: ApplesaucePool;\n readonly tiers: RelayTiers;\n readonly storage: StorageLike;\n readonly network: NostrNetworkInterface;\n readonly inboxRelays: InboxRelays;\n /** Register background work so reads can wait for it. */\n readonly track: (work: Promise<unknown>) => void;\n /** File a message the session read or wrote. */\n readonly deliver: (message: DmMessage, participants: readonly string[]) => void;\n}\n\n/** One account's group client and the subscriptions that feed it. */\nexport interface GroupSession {\n readonly self: string;\n /** Resolves once the client has loaded its groups and listens for invitations. */\n readonly ready: Promise<MarmotClient>;\n /** The group with exactly these other members, created and joined by invitation when there is none. */\n groupFor(client: MarmotClient, others: readonly string[]): Promise<MarmotGroup>;\n /** A group this device belongs to; `invalid:unknown-conversation` otherwise. */\n existing(client: MarmotClient, conversationId: string): MarmotGroup;\n close(): void;\n}\n\nasync function drain(results: AsyncIterable<unknown>): Promise<void> {\n const iterator = results[Symbol.asyncIterator]();\n while (!(await iterator.next()).done);\n}\n\nasync function openClient(network: NostrNetworkInterface, sealed: SealedGroupStoreOptions): Promise<MarmotClient> {\n const device = createSealedGroupStore<string>(sealed, 'device');\n const clientId = (await device.getItem('client-id')) ?? (await device.setItem('client-id', bytesToHex(crypto.getRandomValues(new Uint8Array(32)))));\n return new MarmotClient({\n signer: sealed.signer,\n network,\n clientId,\n groupStateStore: createSealedGroupStore(sealed, 'groups'),\n keyPackageStore: createSealedGroupStore(sealed, 'key-packages'),\n inviteStore: createSealedGroupStore(sealed, 'invites'),\n lifecycleStore: createSealedGroupStore(sealed, 'lifecycle'),\n ingestStateStore: createSealedGroupStore(sealed, 'ingest'),\n });\n}\n\n/**\n * Everyone in a group, the account included, sorted.\n *\n * @param group - A group this device belongs to.\n * @returns Member public keys.\n * @example\n * ```ts\n * membersOf(group); // ['<alice>', '<bob>']\n * ```\n */\nexport function membersOf(group: MarmotGroup): string[] {\n return getGroupMemberPubkeys(group.state).sort();\n}\n\n/**\n * A group's conversation id: its group id in hex.\n *\n * @param group - A group this device belongs to.\n * @returns The id the backend files the group's messages under.\n * @example\n * ```ts\n * groupIdOf(group); // '8f3a…'\n * ```\n */\nexport function groupIdOf(group: MarmotGroup): string {\n return bytesToHex(group.id);\n}\n\n/**\n * Start a group session for one account: open the group library over sealed\n * storage, publish a key package so others can invite the account, follow\n * the group events of every group it belongs to, and join the groups it is\n * invited to as the invitations open. Group events are applied in arrival\n * order, one group at a time, because each one moves the group's secrets on.\n *\n * @param context - Pool, tiers, storage and the backend's hooks.\n * @param self - The account's public key.\n * @param signer - The account's signer; it needs `nip44`.\n * @returns The session; `close` drops its subscriptions.\n * @example\n * ```ts\n * const session = openGroupSession(context, me, signer);\n * const client = await session.ready;\n * const group = await session.groupFor(client, [alice]);\n * ```\n */\nexport function openGroupSession(context: GroupSessionContext, self: string, signer: ISigner): GroupSession {\n const handles: EoseSubscription[] = [];\n const chains = new Map<string, Promise<void>>();\n let invites: Promise<void> = Promise.resolve();\n let closed = false;\n const groupRelays = (): string[] => mergeRelaySets(context.tiers.get().outbox, context.tiers.get().super);\n\n const receive = (group: MarmotGroup, data: Uint8Array): void => {\n const rumor = deserializeApplicationData(data);\n if (rumor.kind !== CHAT_KIND) return;\n // The library delivers only other members' messages, and an account is one member, so nothing read here is the user's own.\n const message: DmMessage = { id: rumor.id, conversationId: groupIdOf(group), senderPubkey: rumor.pubkey, createdAt: rumor.created_at, content: rumor.content, status: 'received' };\n context.deliver(message, membersOf(group));\n };\n\n const watch = (client: MarmotClient, group: MarmotGroup): void => {\n const id = groupIdOf(group);\n group.on('applicationMessage', (data) => receive(group, data));\n const filter = { kinds: [GROUP_EVENT_KIND], '#h': [bytesToHex(group.groupData?.nostrGroupId as Uint8Array)] };\n const handle = subscribeWithEose(context.pool, mergeRelaySets(group.relays), [filter], (item) => {\n if (item === 'EOSE') return;\n const next = (chains.get(id) ?? Promise.resolve()).then(() => drain(client.groups.ingest(id, [item]))).catch(ignore);\n chains.set(id, next);\n context.track(next);\n });\n handles.push(handle);\n };\n\n const publishKeyPackage = async (client: MarmotClient): Promise<void> => {\n const relays = mergeRelaySets(await context.inboxRelays(self), context.tiers.get().outbox);\n await client.keyPackages.ensurePublished({ relays }).catch(ignore);\n };\n\n const accept = (client: MarmotClient, event: NostrEvent): void => {\n invites = invites\n .then(async () => {\n if (!(await client.invites.ingestEvent(event))) return;\n await client.invites.decryptGiftWraps();\n for (const welcomeRumor of await client.invites.getUnread()) {\n await client.invites.markAsRead(welcomeRumor.id);\n watch(client, (await client.joinGroupFromWelcome({ welcomeRumor })).group);\n await publishKeyPackage(client);\n }\n })\n .catch(ignore);\n context.track(invites);\n };\n\n const start = async (): Promise<MarmotClient> => {\n const client = await openClient(context.network, { storage: context.storage, signer, owner: self });\n await publishKeyPackage(client);\n for (const group of await client.groups.loadAll()) watch(client, group);\n const relays = await context.inboxRelays(self);\n if (closed) return client;\n handles.push(\n subscribeWithEose(context.pool, relays, [{ kinds: [kinds.GiftWrap], '#p': [self] }], (item) => {\n if (item !== 'EOSE') accept(client, item);\n }),\n );\n return client;\n };\n\n const keyPackageOf = async (pubkey: string): Promise<NostrEvent> => {\n const relays = mergeRelaySets(await context.inboxRelays(pubkey), groupRelays());\n const found = await context.network.request(relays, [{ kinds: [ADDRESSABLE_KEY_PACKAGE_KIND], authors: [pubkey] }]);\n const latest = found.sort((a, b) => b.created_at - a.created_at)[0];\n if (!latest) throw new Error('unavailable:recipient-not-ready');\n return latest;\n };\n\n return {\n self,\n ready: start(),\n async groupFor(client, others) {\n const wanted = [self, ...others].sort().join(':');\n const known = client.groups.loaded.find((group) => membersOf(group).join(':') === wanted);\n if (known) return known;\n const invitees = await Promise.all(others.map(keyPackageOf));\n const group = await client.groups.create('', { relays: groupRelays(), adminPubkeys: [self], invitees });\n watch(client, group);\n return group;\n },\n existing(client, conversationId) {\n const known = client.groups.loaded.find((group) => groupIdOf(group) === conversationId);\n if (!known) throw new Error('invalid:unknown-conversation');\n return known;\n },\n close() {\n closed = true;\n for (const handle of handles) handle.unsubscribe();\n },\n };\n}\n","import { bytesToHex, hexToBytes } from 'applesauce-core/helpers';\nimport type { ISigner } from 'applesauce-signers';\nimport type { GenericKeyValueStore } from '@internet-privacy/marmot-ts';\nimport type { StorageLike } from '../types.js';\n\n/** NIP-44 encrypts at most 65535 bytes; a UTF-16 code unit takes at most three UTF-8 bytes, so 16384 units always fit. */\nconst SEAL_UNITS = 16_384;\n\n/** What {@link createSealedGroupStore} needs. */\nexport interface SealedGroupStoreOptions {\n readonly storage: StorageLike;\n /** The account signer; the store is encrypted to `owner` with its `nip44`. */\n readonly signer: ISigner;\n readonly owner: string;\n}\n\n/** The group library keeps bytes and big integers; JSON keeps neither, so both are tagged. */\nfunction encode(_key: string, value: unknown): unknown {\n if (value instanceof Uint8Array) return { $bytes: bytesToHex(value) };\n if (typeof value === 'bigint') return { $bigint: value.toString() };\n return value;\n}\n\nfunction decode(_key: string, value: unknown): unknown {\n if (value === null || typeof value !== 'object') return value;\n if ('$bytes' in value) return hexToBytes(String(value.$bytes));\n if ('$bigint' in value) return BigInt(String(value.$bigint));\n return value;\n}\n\n/**\n * One of the group library's key-value stores, sealed to the account. The\n * library keeps group secrets, its own signing keys and pending invites in\n * these stores; kernl writes each store to `storage` as one value that the\n * account signer encrypted to itself with `nip44`, split into parts NIP-44\n * can carry. Nothing readable reaches `storage`, so the key rule in\n * `SOUL.md` opinion 1 holds for every secret the library generates (D-018).\n *\n * The store is decrypted once and then served from memory, so an extension\n * or remote signer is asked once per store per page load. Writes are applied\n * in order.\n *\n * @param options - Backing storage, the account signer and its public key.\n * @param name - Which of the library's stores this is; part of the storage key.\n * @returns A `GenericKeyValueStore` for `MarmotClient`.\n * @example\n * ```ts\n * const groupStateStore = createSealedGroupStore({ storage: localStorage, signer: account, owner: account.pubkey }, 'groups');\n * await groupStateStore.setItem('note', new Uint8Array([1, 2]));\n * await groupStateStore.getItem('note'); // Uint8Array [1, 2]\n * ```\n */\nexport function createSealedGroupStore<T>(options: SealedGroupStoreOptions, name: string): GenericKeyValueStore<T> {\n const { storage, owner } = options;\n const nip44 = options.signer.nip44 as NonNullable<ISigner['nip44']>;\n const key = `kernl:group:v1:${owner}:${name}`;\n\n const open = async (): Promise<Map<string, T>> => {\n const raw = storage.getItem(key);\n if (raw === null) return new Map();\n const parts = await Promise.all((JSON.parse(raw) as string[]).map((part) => nip44.decrypt(owner, part)));\n return new Map(Object.entries(JSON.parse(parts.join(''), decode) as Record<string, T>));\n };\n const loading = open();\n let writes: Promise<unknown> = loading;\n\n const seal = async (entries: Map<string, T>): Promise<void> => {\n const text = JSON.stringify(Object.fromEntries(entries), encode);\n const parts: string[] = [];\n for (let start = 0; start < text.length; start += SEAL_UNITS) parts.push(text.slice(start, start + SEAL_UNITS));\n storage.setItem(key, JSON.stringify(await Promise.all(parts.map((part) => nip44.encrypt(owner, part)))));\n };\n const write = (change: (entries: Map<string, T>) => void): Promise<void> => {\n const next = writes.then(async () => {\n const entries = await loading;\n change(entries);\n await seal(entries);\n });\n writes = next;\n return next;\n };\n\n return {\n async getItem(item) {\n return (await loading).get(item) ?? null;\n },\n async setItem(item, value) {\n await write((entries) => entries.set(item, value));\n return value;\n },\n removeItem: (item) => write((entries) => entries.delete(item)),\n clear: () => write((entries) => entries.clear()),\n async keys() {\n return [...(await loading).keys()];\n },\n };\n}\n","import {\n createBridgeRegistry,\n createHandoffBackends,\n createHttpBridge,\n createMailBridge,\n createNzbBridge,\n createSoulseekBridge,\n createTorrentBridge,\n type BridgeRegistry,\n type BridgeRegistryOptions,\n type HandoffOpener,\n type HttpBridgeOptions,\n type TorrentBackend,\n} from '@kernlize/bridges';\n\n/** Options for {@link createDefaultBridges}. */\nexport interface DefaultBridgesOptions extends BridgeRegistryOptions {\n /** Passed to the web bridge: policy overrides, fetch and host resolver. */\n readonly http?: HttpBridgeOptions;\n /**\n * Opens a URI with an app on the user's device. When given, downloads, sharing and\n * mail resolve by handing the locator off through it; without it they report `unavailable`.\n */\n readonly handoff?: HandoffOpener;\n /**\n * The engine for magnet links, such as `createWebTorrentBackend`. It wins over the\n * hand-off for downloads from peers; the other bridges still hand off (D-017).\n */\n readonly torrent?: TorrentBackend;\n}\n\n/**\n * The shell's bridge registry: the web bridge, complete, plus the downloads, sharing\n * and mail bridges. With a `handoff` opener those four hand each locator to an app on\n * the user's device; without one they report `unavailable` (D-010). A `torrent` backend\n * replaces the hand-off for magnet links, so they download inside kernl (D-017).\n *\n * @param options - Consent hook, outcome observer, web bridge options, the hand-off opener and the torrent backend.\n * @returns A `BridgeRegistry`.\n * @example\n * ```ts\n * createDefaultBridges().forScheme('magnet')?.availability(); // { available: false, reason: 'no-backend' }\n * const bridges = createDefaultBridges({ handoff: (uri) => host.openLink(uri) });\n * bridges.forScheme('magnet')?.availability(); // { available: true, handoff: true }\n * const inKernl = createDefaultBridges({ handoff, torrent: createWebTorrentBackend({ client }) });\n * inKernl.forScheme('magnet')?.availability(); // { available: true }\n * ```\n */\nexport function createDefaultBridges(options: DefaultBridgesOptions = {}): BridgeRegistry {\n const { http, handoff, torrent, ...registryOptions } = options;\n const registry = createBridgeRegistry(registryOptions);\n const backends = handoff ? createHandoffBackends(handoff) : undefined;\n registry.register(createHttpBridge(http));\n registry.register(createTorrentBridge(torrent ?? backends?.torrent));\n registry.register(createNzbBridge(backends?.nzb));\n registry.register(createSoulseekBridge(backends?.soulseek));\n registry.register(createMailBridge(backends?.mail));\n return registry;\n}\n","import type { DmAdapter } from '@kehto/services';\nimport type { DmConversation } from '@napplet/core';\nimport type { Profiles } from '../profiles/profiles.js';\n\n/**\n * Name the people in every conversation the shell lists for an applet.\n *\n * A messaging backend knows keys; a person knows names. Each participant\n * without a label is given the name from their published profile, read from\n * the store or cache at once and otherwise looked up until it is found or\n * every lookup server has answered. A participant with no profile keeps no\n * label, so the applet still shows its own short form. A label the backend\n * already gave is kept: it is how that provider names the person (D-031).\n *\n * @param adapter - The composite messaging adapter kehto's `dm` service routes to.\n * @param profiles - The shell's profile service.\n * @returns The same adapter with participants named.\n * @example\n * ```ts\n * createDmService({ adapter: labelConversations(messaging.composite(), kernl.profiles) });\n * ```\n */\nexport function labelConversations(adapter: DmAdapter, profiles: Pick<Profiles, 'settled'>): DmAdapter {\n const named = async (conversation: DmConversation): Promise<DmConversation> => {\n const participants = await Promise.all(\n conversation.participants.map(async (peer) => {\n if (peer.label) return peer;\n const card = await profiles.settled(peer.pubkey);\n return card.found ? { ...peer, label: card.name } : peer;\n }),\n );\n return { ...conversation, participants };\n };\n return {\n ...adapter,\n async conversations(query) {\n const page = await adapter.conversations(query);\n return { ...page, conversations: await Promise.all(page.conversations.map(named)) };\n },\n };\n}\n","import { BehaviorSubject, catchError, EMPTY, endWith, firstValueFrom, ignoreElements, map, of, switchMap, type Observable } from 'rxjs';\nimport type { EventStore } from 'applesauce-core';\nimport { unixNow } from 'applesauce-core/helpers';\nimport { BLOSSOM_SERVER_LIST_KIND, getBlossomServersFromList, normalizeBlossomServer } from 'applesauce-common/helpers';\nimport type { ISigner } from 'applesauce-signers';\nimport type { NostrEvent } from '@napplet/core';\nimport type { ApplesaucePool } from '../applesauce/relay-hooks.js';\nimport { summarizePublish, type PublishOutcome } from '../relays/publish-outcome.js';\nimport type { ProfilePointer } from '../profiles/profiles.js';\n\n/**\n * File servers to use when the account has not published its own list: public\n * Blossom servers that answered an upload preflight when this was chosen.\n *\n * @example\n * ```ts\n * DEFAULT_FILE_SERVERS[0]; // 'https://blossom.primal.net/'\n * ```\n */\nexport const DEFAULT_FILE_SERVERS: readonly string[] = Object.freeze(['https://blossom.primal.net/', 'https://nostr.download/', 'https://blossom.band/']);\n\n/** Where the account's files go: its published list (BUD-03, kind 10063), or the defaults while it has none. */\nexport type FileServerState =\n | { readonly status: 'loading' }\n | { readonly status: 'missing'; readonly servers: readonly string[] }\n | { readonly status: 'found'; readonly servers: readonly string[]; readonly event: NostrEvent };\n\n/** The signed-in account's file servers. */\nexport interface AccountFileServers {\n readonly state$: Observable<FileServerState>;\n state(): FileServerState;\n /** The servers an upload goes to now: the published list once it is known, else the defaults. Waits only while the list is being looked up. */\n current(): Promise<readonly string[]>;\n /** Publish a new list. Rejects with `denied:read-only` or `invalid:server-url`. */\n save(servers: readonly string[]): Promise<PublishOutcome>;\n}\n\n/** Options for {@link createAccountFileServers}. */\nexport interface AccountFileServersOptions {\n readonly store: EventStore;\n readonly pool: Pick<ApplesaucePool, 'publish'>;\n /** Loads a replaceable event into the store and completes when the servers asked have answered. */\n readonly load: (pointer: ProfilePointer) => Observable<NostrEvent>;\n readonly pubkey$: Observable<string | undefined>;\n readonly pubkey: () => string | undefined;\n /** Where the list is looked up, and published to besides the account's outboxes. */\n readonly lookupRelays: () => readonly string[];\n /** Where the account publishes. */\n readonly outboxes: () => readonly string[];\n readonly signer: () => Pick<ISigner, 'signEvent'> | undefined;\n /** The servers used when no list is published; {@link DEFAULT_FILE_SERVERS} by default. */\n readonly defaults?: readonly string[];\n}\n\n/**\n * The servers a file-server list names, in its order, as root URLs.\n *\n * @param event - A kind 10063 list, or nothing.\n * @returns Server URLs, deduplicated.\n * @example\n * ```ts\n * fileServersFromEvent(list); // ['https://blossom.primal.net/']\n * ```\n */\nexport function fileServersFromEvent(event: NostrEvent | undefined): readonly string[] {\n return event ? [...new Set(getBlossomServersFromList(event).map((url) => url.href))] : [];\n}\n\n/**\n * The tags of a new file-server list: one `server` tag per server, in order,\n * with every other tag of the previous list kept.\n *\n * @param servers - Server URLs or hostnames.\n * @param previous - The list being replaced.\n * @returns Tags for a kind 10063 event. Throws `invalid:server-url` for something that is not a server.\n * @example\n * ```ts\n * fileServerTags(['blossom.primal.net']); // [['server', 'https://blossom.primal.net/']]\n * ```\n */\nexport function fileServerTags(servers: readonly string[], previous?: NostrEvent): string[][] {\n const urls = servers.map((server) => {\n try {\n return normalizeBlossomServer(server).href;\n } catch {\n throw new Error('invalid:server-url');\n }\n });\n const kept = (previous?.tags ?? []).filter((tag) => tag[0] !== 'server');\n return [...[...new Set(urls)].map((url) => ['server', url]), ...kept];\n}\n\nfunction stateFor(options: AccountFileServersOptions, pubkey: string | undefined): Observable<FileServerState> {\n const defaults = options.defaults ?? DEFAULT_FILE_SERVERS;\n if (pubkey === undefined) return of({ status: 'missing', servers: defaults });\n // The list is looked up until every server asked has answered; only then do the defaults stand in.\n const answered = options.load({ kind: BLOSSOM_SERVER_LIST_KIND, pubkey, relays: [...options.lookupRelays()] }).pipe(catchError(() => EMPTY), ignoreElements(), endWith(true));\n return options.store.replaceable(BLOSSOM_SERVER_LIST_KIND, pubkey).pipe(\n switchMap((event) => {\n if (event) return of<FileServerState>({ status: 'found', servers: fileServersFromEvent(event), event });\n return answered.pipe(map((): FileServerState => ({ status: 'missing', servers: defaults })));\n }),\n );\n}\n\n/**\n * Follow the active account's file-server list (BUD-03) and save a new one.\n *\n * Uploads go to these servers in order: the first gets the file, the rest\n * mirror it. An account with no published list uses the defaults. Saving signs\n * the list and publishes it to the account's outboxes and the lookup servers;\n * it succeeds when any of them accepts it (D-028).\n *\n * @param options - Store, pool, loader, account, servers and signer.\n * @returns The account's file servers.\n * @example\n * ```ts\n * const files = createAccountFileServers({ store, pool, load, pubkey$, pubkey, lookupRelays, outboxes, signer });\n * await files.current(); // ['https://blossom.primal.net/', …]\n * ```\n */\nexport function createAccountFileServers(options: AccountFileServersOptions): AccountFileServers {\n const state$ = new BehaviorSubject<FileServerState>({ status: 'loading' });\n options.pubkey$.pipe(switchMap((pubkey) => stateFor(options, pubkey))).subscribe((state) => state$.next(state));\n return {\n state$: state$.asObservable(),\n state: () => state$.value,\n current: () => firstValueFrom(state$.pipe(switchMap((state) => (state.status === 'loading' ? EMPTY : of(state.servers))))),\n async save(servers) {\n const signer = options.signer();\n const pubkey = options.pubkey();\n if (!signer || !pubkey) throw new Error('denied:read-only');\n const previous = options.store.getReplaceable(BLOSSOM_SERVER_LIST_KIND, pubkey);\n const tags = fileServerTags(servers, previous);\n const created_at = Math.max(unixNow(), (previous?.created_at ?? 0) + 1);\n const event = await signer.signEvent({ kind: BLOSSOM_SERVER_LIST_KIND, created_at, tags, content: previous?.content ?? '' });\n const relays = [...new Set([...options.outboxes(), ...options.lookupRelays()])];\n const outcome = await options.pool.publish(relays, event).then(summarizePublish, () => summarizePublish(relays.map((from) => ({ ok: false, from, message: 'publish failed' }))));\n if (outcome.ok) options.store.add(event);\n return outcome;\n },\n };\n}\n","import { Actions, computeBlobSha256, createUploadAuth, type BlobDescriptor, type SignedEvent } from 'blossom-client-sdk';\nimport type { Uploader, UploadRequest, UploadResult } from '@kehto/services';\nimport type { ISigner } from 'applesauce-signers';\nimport type { NostrEvent } from '@napplet/core';\nimport type { AppletIdentity, ConsentSummary, KernlHost } from '../types.js';\n\n/** What the person is asked about before a file leaves for a server. */\nexport interface UploadDetails {\n readonly filename?: string;\n readonly mimeType: string;\n readonly size: number;\n readonly sha256: string;\n readonly servers: readonly string[];\n}\n\n/** Uploads to several servers, the first first and the rest as mirrors; hzrd149's `multiServerUpload` fits. */\nexport type MultiServerUpload = (\n servers: readonly string[],\n blob: Blob,\n options: {\n onAuth: (server: string, sha256: string, type: 'upload' | 'media') => Promise<SignedEvent>;\n onUpload: (server: string) => void;\n onError: (server: string, sha256: string, blob: Blob, error: Error) => void;\n },\n) => Promise<Map<string, BlobDescriptor>>;\n\n/** Options for {@link createBlossomUploader}. */\nexport interface BlossomUploaderOptions {\n /** The servers this upload goes to, in order. */\n readonly servers: () => Promise<readonly string[]>;\n readonly signer: () => Pick<ISigner, 'signEvent'> | undefined;\n /** Asks the person; resolves true only when they allow it. Called once per upload, before anything is signed or sent. */\n readonly ask: (windowId: string, details: UploadDetails) => Promise<boolean>;\n /** The transfer; hzrd149's `Actions.multiServerUpload` by default. */\n readonly transfer?: MultiServerUpload;\n}\n\nconst KIB = 1024;\n\n/**\n * A size as a person reads it.\n *\n * @param bytes - A byte count.\n * @returns `512 bytes`, `1.5 KB`, `3.2 MB`.\n * @example\n * ```ts\n * sizeWords(1_572_864); // '1.5 MB'\n * ```\n */\nexport function sizeWords(bytes: number): string {\n if (bytes < KIB) return `${bytes} ${bytes === 1 ? 'byte' : 'bytes'}`;\n const units = ['KB', 'MB', 'GB'];\n let value = bytes / KIB;\n let unit = 0;\n while (value >= KIB && unit < units.length - 1) {\n value /= KIB;\n unit += 1;\n }\n return `${value.toFixed(1)} ${units[unit]}`;\n}\n\n/**\n * The consent prompt for an upload: what leaves, how big it is, where it goes\n * and who can then fetch it. A file on a public server can be fetched by\n * anyone who has its address, so the prompt says so plainly.\n *\n * @param details - The file and its servers.\n * @param applet - The applet asking.\n * @returns The summary the host renders.\n * @example\n * ```ts\n * describeUpload({ mimeType: 'image/png', size: 2048, sha256, servers }, identity).title; // 'Upload a file'\n * ```\n */\nexport function describeUpload(details: UploadDetails, applet: AppletIdentity): ConsentSummary {\n const hosts = details.servers.map((server) => new URL(server).hostname);\n const draft: NostrEvent = {\n kind: 24242,\n content: 'Upload a file',\n tags: [['t', 'upload'], ['x', details.sha256]],\n created_at: 0,\n pubkey: '',\n id: '',\n sig: '',\n };\n return {\n title: 'Upload a file',\n severity: 'public',\n lines: [\n { label: 'File', after: `${details.filename ? `${details.filename}, ` : ''}${details.mimeType}` },\n { label: 'Size', after: sizeWords(details.size) },\n { label: 'Sent to', after: hosts.join(', ') },\n { label: 'Who can see it', after: 'Anyone who has its address' },\n ],\n applet,\n event: draft,\n };\n}\n\n/**\n * Put an upload to the person through the host's consent prompt. An applet the\n * shell cannot name is refused without asking.\n *\n * @param host - Supplies `presentConsent`.\n * @param applet - The asking applet's identity, if the shell knows it.\n * @param details - The file and its servers.\n * @returns Whether the person allowed it.\n * @example\n * ```ts\n * ask: (windowId, details) => askUploadConsent(host, identityOf(windowId), details);\n * ```\n */\nexport function askUploadConsent(host: Pick<KernlHost, 'presentConsent'>, applet: AppletIdentity | undefined, details: UploadDetails): Promise<boolean> {\n if (!applet) return Promise.resolve(false);\n return new Promise((resolve) => host.presentConsent({ summary: describeUpload(details, applet), resolve }));\n}\n\nconst asBlob = (request: UploadRequest): Blob => (request.data instanceof Blob ? request.data : new Blob([request.data], request.mimeType ? { type: request.mimeType } : {}));\n\nfunction failed(uploadId: string, error: string, status: 'failed' | 'cancelled' = 'failed'): UploadResult {\n return { ok: false, uploadId, status, rail: 'blossom', error };\n}\n\nfunction completed(uploadId: string, stored: readonly BlobDescriptor[], mimeType: string): UploadResult {\n const [first, ...rest] = stored as [BlobDescriptor, ...BlobDescriptor[]];\n const type = first.type ?? mimeType;\n return {\n ok: true,\n uploadId,\n status: 'complete',\n rail: 'blossom',\n url: first.url,\n ...(rest.length ? { fallbackUrls: rest.map((descriptor) => descriptor.url) } : {}),\n sha256: first.sha256,\n size: first.size,\n mimeType: type,\n nip94: [['url', first.url], ['x', first.sha256], ['m', type], ['size', String(first.size)], ...rest.map((descriptor) => ['fallback', descriptor.url])],\n };\n}\n\n/**\n * kernl's upload backend for kehto's `createUploadService`: Blossom over\n * hzrd149's client SDK. The file goes to the account's first file server and\n * is mirrored to the others; any server that stores it makes the upload a\n * success, and the result names every copy (D-028). The person is asked first,\n * once per file, with what it is, its size and where it goes; nothing is signed\n * or sent unless they allow it. A read-only session cannot upload. An applet\n * never chooses the servers (D-033).\n *\n * @param options - Servers, signer, the consent question and an optional transfer for tests.\n * @returns An `Uploader`.\n * @example\n * ```ts\n * registry.upload = createUploadService({ uploader: createBlossomUploader({ servers: files.current, signer, ask }) });\n * ```\n */\nexport function createBlossomUploader(options: BlossomUploaderOptions): Uploader {\n const transfer: MultiServerUpload = options.transfer ?? Actions.multiServerUpload;\n return {\n async upload(request, ctx) {\n const signer = options.signer();\n if (!signer) return failed(ctx.uploadId, 'denied:read-only');\n const blob = asBlob(request);\n const servers = await options.servers();\n if (servers.length === 0) return failed(ctx.uploadId, 'unavailable:no-file-server');\n const sha256 = await computeBlobSha256(blob);\n const mimeType = blob.type || 'application/octet-stream';\n const details: UploadDetails = { mimeType, size: blob.size, sha256, servers, ...(request.filename ? { filename: request.filename } : {}) };\n if (!(await options.ask(ctx.windowId, details))) return failed(ctx.uploadId, 'denied:consent', 'cancelled');\n let auth: Promise<SignedEvent> | undefined;\n const signEvent = (draft: Parameters<ISigner['signEvent']>[0]): Promise<SignedEvent> => signer.signEvent(draft) as Promise<SignedEvent>;\n const stored = await transfer(servers, blob, {\n // One authorization covers the file on every server, so the signer is asked once.\n onAuth: (_server, hash) => (auth ??= createUploadAuth(signEvent, hash)),\n onUpload: () => {\n ctx.onStatus({ ok: true, uploadId: ctx.uploadId, status: 'uploading', rail: 'blossom', bytesSent: blob.size, bytesTotal: blob.size, updatedAt: Date.now() });\n },\n onError: () => undefined,\n }).catch(() => new Map<string, BlobDescriptor>());\n if (stored.size === 0) return failed(ctx.uploadId, `unavailable:not-accepted:0/${servers.length}`);\n return completed(ctx.uploadId, servers.flatMap((server) => stored.get(server) ?? []), mimeType);\n },\n };\n}\n","import { map, takeUntil, type Observable } from 'rxjs';\nimport type { EventStore } from 'applesauce-core';\nimport type { RelayPool } from 'applesauce-relay';\nimport type { AccountManager } from 'applesauce-accounts';\nimport type { ISigner } from 'applesauce-signers';\nimport type { AddressPointerLoader } from 'applesauce-loaders/loaders';\nimport type { KernlOptions, RelayTiers } from './types.js';\nimport { isReadOnlyAccount } from './applesauce/auth-hooks.js';\nimport { createReplaceableLoader, lookupRelaysOf } from './applesauce/identity-providers.js';\nimport { connectEventCache, type ConnectedEventCache } from './cache/connect.js';\nimport { createProfiles, type Profiles } from './profiles/profiles.js';\nimport { createRelayDirectory, type RelayDirectory } from './relays/directory.js';\nimport { createAccountMailboxes, type AccountMailboxes } from './relays/mailboxes.js';\nimport { createAccountFileServers, type AccountFileServers } from './files/file-servers.js';\n\n/** The parts of the shell that know people and servers: the event cache, the loader over it, profiles, mailboxes and the directory. */\nexport interface KernlNetwork {\n readonly eventCache: ConnectedEventCache;\n readonly replaceableLoader: AddressPointerLoader;\n readonly profiles: Profiles;\n readonly directory: RelayDirectory;\n readonly mailboxes: AccountMailboxes;\n readonly files: AccountFileServers;\n /** The active account's signer, or none for a read-only or signed-out session. */\n readonly signer: () => ISigner | undefined;\n}\n\n/** What {@link createKernlNetwork} composes over. */\nexport interface KernlNetworkParts {\n readonly eventStore: EventStore;\n readonly pool: RelayPool;\n readonly tiers: RelayTiers;\n readonly accounts: AccountManager;\n /** Completes the mailboxes' account stream when the shell is destroyed. */\n readonly destroyed$: Observable<void>;\n}\n\n/**\n * Compose the event cache, the replaceable loader that asks it first, the\n * profile service, the relay directory, and the active account's mailboxes\n * and file servers.\n * A read-only or signed-out session has no signer for the mailboxes, so a\n * save is refused with `denied:read-only` (D-029, D-030).\n *\n * @param options - The shell's options; `eventCache` opens the cache.\n * @param parts - The store, pool, tiers and accounts they share.\n * @returns The composed parts.\n * @example\n * ```ts\n * const network = createKernlNetwork(options, { eventStore, pool, tiers, accounts, destroyed$ });\n * network.profiles.card$(pubkey).subscribe(render);\n * ```\n */\nexport function createKernlNetwork(options: Pick<KernlOptions, 'eventCache'>, parts: KernlNetworkParts): KernlNetwork {\n const { eventStore, pool, tiers, accounts } = parts;\n const eventCache = connectEventCache(eventStore, options.eventCache);\n const replaceableLoader = createReplaceableLoader(eventStore, pool, tiers, eventCache.cacheRequest);\n const lookupRelays = (): string[] => lookupRelaysOf(tiers.get());\n const directory = createRelayDirectory({ pool });\n const signer = (): ISigner | undefined => (accounts.active && !isReadOnlyAccount(accounts.active) ? accounts.active.signer : undefined);\n const mailboxes = createAccountMailboxes({\n store: eventStore,\n pool,\n pubkey$: accounts.active$.pipe(map((account) => account?.pubkey), takeUntil(parts.destroyed$)),\n lookupRelays,\n signer,\n directory,\n });\n const profiles = createProfiles({ store: eventStore, load: replaceableLoader, lookupRelays });\n const files = createAccountFileServers({\n store: eventStore,\n pool,\n load: replaceableLoader,\n pubkey$: accounts.active$.pipe(map((account) => account?.pubkey), takeUntil(parts.destroyed$)),\n pubkey: () => accounts.active?.pubkey,\n lookupRelays,\n outboxes: () => tiers.get().outbox,\n signer,\n });\n return { eventCache, replaceableLoader, profiles, directory, mailboxes, files, signer };\n}\n","import { catchError, distinctUntilChanged, EMPTY, endWith, filter, firstValueFrom, ignoreElements, map, merge, Observable, share, switchMap, take, timer, type Subscription } from 'rxjs';\nimport type { EventStore } from 'applesauce-core';\nimport { getDisplayName, getOutboxes, getProfileContent, getProfilePicture } from 'applesauce-core/helpers';\nimport type { NostrEvent } from '@napplet/core';\nimport { abbreviate } from '../consent/describe-change.js';\n\n/** How a person is shown: their chosen name and picture, or a short key while none is known. */\nexport interface ProfileCard {\n readonly pubkey: string;\n /** Display name, then name, then the abbreviated key. */\n readonly name: string;\n /** An `https:` picture URL, never another scheme. */\n readonly picture?: string;\n readonly nip05?: string;\n readonly about?: string;\n /** Whether a profile event has been seen; false while the name is the abbreviated key. */\n readonly found: boolean;\n}\n\n/** A replaceable pointer the loader understands. */\nexport interface ProfilePointer {\n readonly kind: number;\n readonly pubkey: string;\n readonly relays?: string[];\n}\n\n/** Loads a replaceable event into the store; applesauce's address loader fits. */\nexport type ProfileLoader = (pointer: ProfilePointer) => Observable<NostrEvent>;\n\n/** People's profiles, read from the shell's event store and loaded on demand. */\nexport interface Profiles {\n /** The card now, and again every time a newer profile arrives. Subscribing starts the lookup. */\n card$(pubkey: string): Observable<ProfileCard>;\n /** The card from what the store already holds, without asking anyone. */\n card(pubkey: string): ProfileCard;\n /** The card once the profile is found, or once the lookup servers have all answered without it; never on a timer. */\n settled(pubkey: string): Promise<ProfileCard>;\n}\n\n/** Options for {@link createProfiles}. */\nexport interface ProfilesOptions {\n readonly store: EventStore;\n readonly load: ProfileLoader;\n /** Where to look besides the author's own servers; usually the discovery and general tiers. */\n readonly lookupRelays: () => readonly string[];\n /** How long an unwatched card keeps its subscription open, in milliseconds. */\n readonly keepAliveMs?: number;\n}\n\nconst PROFILE_KIND = 0;\nconst MAILBOX_KIND = 10002;\nconst KEEP_ALIVE_MS = 60_000;\nconst HEX_KEY = /^[0-9a-f]{64}$/;\n\nfunction safePicture(event: NostrEvent): string | undefined {\n const picture = getProfilePicture(event);\n return picture?.startsWith('https://') ? picture : undefined;\n}\n\n/**\n * Read a profile card from a profile event, or the placeholder for a key with none.\n *\n * @param pubkey - The person's hex key.\n * @param event - Their newest profile event, if any.\n * @returns The card.\n * @example\n * ```ts\n * toProfileCard(pubkey, undefined).name; // '3bf0c63f…'\n * toProfileCard(pubkey, profileEvent).name; // 'fiatjaf'\n * ```\n */\nexport function toProfileCard(pubkey: string, event: NostrEvent | undefined): ProfileCard {\n const fallback = abbreviate(pubkey);\n const content = event ? getProfileContent(event) : undefined;\n if (!event || !content) return Object.freeze({ pubkey, name: fallback, found: false });\n const name = getDisplayName(content)?.trim();\n const picture = safePicture(event);\n return Object.freeze({\n pubkey,\n name: name || fallback,\n found: true,\n ...(picture ? { picture } : {}),\n ...(content.nip05 ? { nip05: content.nip05 } : {}),\n ...(content.about ? { about: content.about } : {}),\n });\n}\n\n/**\n * The profile service the shell shows people through.\n *\n * A card subscription asks the lookup relays for the person's profile and\n * their relay list at once; when the relay list names servers the profile\n * was not found on, the profile is asked for there as well, because a\n * profile lives on its author's own servers first (NIP-65). Nothing gives\n * up on a timer: a profile that arrives late replaces the placeholder.\n *\n * @param options - The store, the loader and the lookup relays.\n * @returns Profile cards per key.\n * @example\n * ```ts\n * const profiles = createProfiles({ store, load: loader, lookupRelays: () => tiers.get().discovery });\n * profiles.card$(pubkey).subscribe((card) => (label.textContent = card.name));\n * ```\n */\nexport function createProfiles(options: ProfilesOptions): Profiles {\n const { store, load } = options;\n const keepAlive = options.keepAliveMs ?? KEEP_ALIVE_MS;\n const cards = new Map<string, Observable<ProfileCard>>();\n\n const lookup = (pubkey: string): Subscription => {\n const relays = [...options.lookupRelays()];\n const subscription = load({ kind: PROFILE_KIND, pubkey, relays }).subscribe({ error: () => undefined });\n // The author's own servers, once their list is known, for a profile the lookup relays do not hold.\n const outboxes = load({ kind: MAILBOX_KIND, pubkey, relays })\n .pipe(\n map((event) => getOutboxes(event).filter((url) => !relays.includes(url))),\n filter((urls) => urls.length > 0 && !store.getReplaceable(PROFILE_KIND, pubkey)),\n take(1),\n switchMap((urls) => load({ kind: PROFILE_KIND, pubkey, relays: urls })),\n )\n .subscribe({ error: () => undefined });\n subscription.add(outboxes);\n return subscription;\n };\n\n const watch = (pubkey: string): Observable<ProfileCard> =>\n new Observable<ProfileCard>((subscriber) => {\n const loading = HEX_KEY.test(pubkey) ? lookup(pubkey) : undefined;\n const updates = store\n .replaceable(PROFILE_KIND, pubkey)\n .pipe(\n map((event) => toProfileCard(pubkey, event)),\n distinctUntilChanged((a, b) => JSON.stringify(a) === JSON.stringify(b)),\n )\n .subscribe(subscriber);\n return () => {\n updates.unsubscribe();\n loading?.unsubscribe();\n };\n }).pipe(share({ resetOnRefCountZero: () => timer(keepAlive) }));\n\n const card = (pubkey: string): ProfileCard => toProfileCard(pubkey, store.getReplaceable(PROFILE_KIND, pubkey.toLowerCase()));\n\n const profiles: Profiles = {\n card$(pubkey) {\n const key = pubkey.toLowerCase();\n let card = cards.get(key);\n if (!card) {\n card = watch(key);\n cards.set(key, card);\n }\n return card;\n },\n card,\n settled(pubkey) {\n const key = pubkey.toLowerCase();\n if (!HEX_KEY.test(key)) return Promise.resolve(card(key));\n const found = profiles.card$(key).pipe(filter((next) => next.found));\n const answered = load({ kind: PROFILE_KIND, pubkey: key, relays: [...options.lookupRelays()] }).pipe(\n catchError(() => EMPTY),\n ignoreElements(),\n endWith(undefined),\n map(() => card(key)),\n );\n return firstValueFrom(merge(found, answered));\n },\n };\n return profiles;\n}\n","import type { EventStore } from 'applesauce-core';\nimport { verifyEvent } from 'applesauce-core/helpers';\nimport type { AuthHooks } from '@kehto/shell';\nimport type { ServiceHandler, ServiceRegistry, Signer } from '@kehto/runtime';\nimport {\n createDmService,\n createIdentityService,\n createLinkService,\n createNotifyService,\n createOutboxService,\n createRelayPoolOutboxRouter,\n createRelayPoolService,\n createResourceService,\n createThemeService,\n createUploadService,\n type DmService,\n type OutboxRouter,\n type RelayListEntry,\n type ResourceFetchInit,\n type ThemeService,\n type Uploader,\n} from '@kehto/services';\nimport type { Theme } from '@napplet/nap/theme/types';\nimport type { EventTemplate, NostrEvent } from '@napplet/core';\nimport { createBridgeResourceResolver, type BridgeContext, type BridgeRegistry, type ResourceResolveInit } from '@kernlize/bridges';\nimport type { MessagingRegistry } from '@kernlize/messaging';\nimport type { KernlHost, RelayTiers } from './types.js';\nimport type { ApplesaucePool } from './applesauce/relay-hooks.js';\nimport { createAppletRelayBackend, createOutboxRelayPool } from './applesauce/relay-backend.js';\nimport { createIdentityProviders, type IdentityProviders, type RelayPermissions } from './applesauce/identity-providers.js';\nimport type { SigningConsent, SigningTemplate } from './consent/handler.js';\nimport { labelConversations } from './messaging/label-conversations.js';\nimport type { Profiles } from './profiles/profiles.js';\n\n/**\n * Whether a host-supplied theme has the colours NAP-THEME requires.\n *\n * @param value - The `theme` option as the host passed it.\n * @returns True when `colors.background`, `colors.text` and `colors.primary` are strings.\n * @example\n * ```ts\n * isTheme({ colors: { background: '#000', text: '#fff', primary: '#7aa2f7' } }); // true\n * ```\n */\nexport function isTheme(value: Record<string, unknown> | undefined): value is Record<string, unknown> & Theme {\n const colors = value?.colors;\n if (typeof colors !== 'object' || colors === null) return false;\n const { background, text, primary } = colors as Record<string, unknown>;\n return typeof background === 'string' && typeof text === 'string' && typeof primary === 'string';\n}\n\n/**\n * Protocols an applet may ask the shell to open.\n *\n * @example\n * ```ts\n * LINK_PROTOCOLS.includes(new URL('mailto:a@example.com').protocol); // true\n * LINK_PROTOCOLS.includes('javascript:'); // false\n * ```\n */\nexport const LINK_PROTOCOLS: readonly string[] = Object.freeze(['https:', 'mailto:']);\n\n/** What the services need from the rest of the shell. */\nexport interface KernlServiceDeps {\n readonly pool: ApplesaucePool;\n readonly tiers: RelayTiers;\n readonly eventStore: EventStore;\n /** `getUserPubkey` lets the identity service name a read-only account, which has no signer. */\n readonly auth: Pick<AuthHooks, 'getSigner'> & Partial<Pick<AuthHooks, 'getUserPubkey'>>;\n /** Gates the outbox service's publishes, which kehto signs without naming the window. */\n readonly consent: SigningConsent;\n readonly host: Pick<KernlHost, 'notify' | 'openLink'>;\n readonly bridges: BridgeRegistry;\n readonly messaging: MessagingRegistry;\n /** Uploads for applets (NAP-UPLOAD); without it the `upload` domain is not offered. */\n readonly uploader?: Uploader;\n /** Names conversation participants for applets; without it they are listed by key alone. */\n readonly profiles?: Pick<Profiles, 'settled'>;\n readonly theme?: Theme;\n /** Maps a live window to its verified identity, or null. */\n readonly resolveIdentity: (windowId: string) => { dTag: string; aggregateHash: string } | null;\n /** Identity lookups; defaults to the applesauce-backed providers. */\n readonly identity?: IdentityProviders;\n}\n\n/** The registered services plus the handles the shell keeps calling. */\nexport interface KernlServices {\n readonly registry: ServiceRegistry;\n readonly theme: ThemeService;\n readonly dm: DmService;\n}\n\nfunction toRelayListEntry(relays: RelayPermissions): RelayListEntry {\n const entries = Object.entries(relays);\n return {\n read: entries.filter(([, flags]) => flags.read).map(([url]) => url),\n write: entries.filter(([, flags]) => flags.write).map(([url]) => url),\n };\n}\n\nfunction withShellWrites(entry: RelayListEntry, tiers: KernlServiceDeps['tiers']): RelayListEntry {\n const { outbox, super: shared } = tiers.get();\n return { read: entry.read, write: [...new Set([...outbox, ...shared])] };\n}\n\n/**\n * kehto's outbox router fails a publish unless every one of the author's\n * write relays accepted it. On an open network one server refusing or being\n * down is ordinary, so kernl reports success when any relay accepted, and\n * keeps the per-relay results so the caller sees how many did (D-028).\n * Upstream gap: the router has no acceptance policy option.\n *\n * @param router - kehto's outbox router.\n * @returns The same router with partial acceptance treated as success.\n * @example\n * ```ts\n * createOutboxService({ router: acceptAnyRelay(createRelayPoolOutboxRouter(options)) });\n * ```\n */\nexport function acceptAnyRelay(router: OutboxRouter): OutboxRouter {\n return {\n ...router,\n async publish(template, options) {\n const result = await router.publish(template, options);\n if (result.ok || !result.relays || !Object.values(result.relays).some(Boolean)) return result;\n const { error: _refused, ...accepted } = result;\n return { ...accepted, ok: true };\n },\n };\n}\n\nfunction requesterFor(deps: Pick<KernlServiceDeps, 'resolveIdentity'>, windowId: string | undefined): BridgeContext['requester'] {\n const identity = windowId === undefined ? null : deps.resolveIdentity(windowId);\n return identity ? { dTag: identity.dTag, hash: identity.aggregateHash } : 'shell';\n}\n\n/**\n * Translate the resource service's fetch init into the bridge resolver's,\n * naming the applet that asked so the bridge consent hook can see it.\n *\n * @param deps - Supplies the window-to-identity lookup.\n * @param init - What kehto's resource service passes to `fetch`.\n * @returns The init for `createBridgeResourceResolver`'s resolver.\n * @example\n * ```ts\n * resourceInitFor(deps, { signal, windowId: 'w1' }).requester; // { dTag: 'chat', hash: '…' }\n * ```\n */\nexport function resourceInitFor(deps: Pick<KernlServiceDeps, 'resolveIdentity'>, init: ResourceFetchInit): ResourceResolveInit {\n const requester = requesterFor(deps, init.windowId);\n return init.headers ? { signal: init.signal, requester, headers: init.headers } : { signal: init.signal, requester };\n}\n\n/**\n * The signer the identity service reads the account from. A read-only account\n * has no signer, yet which account is signed in is exactly what it exists to\n * show, so the service gets a view that answers `getPublicKey` and nothing\n * else: an applet the user granted \"your account\" learns who is signed in, and\n * every write still finds no `signEvent` and is refused.\n */\nfunction identitySigner(auth: KernlServiceDeps['auth']): Signer | null {\n const signer = auth.getSigner();\n if (signer) return signer;\n const pubkey = auth.getUserPubkey?.() ?? null;\n return pubkey === null ? null : { getPublicKey: () => pubkey };\n}\n\nfunction createOutbox(deps: KernlServiceDeps, identity: IdentityProviders) {\n const router = createRelayPoolOutboxRouter({\n relayPool: createOutboxRelayPool(deps.pool),\n fallbackRelays: [...deps.tiers.get().super],\n async loadRelayLists(pubkeys) {\n const lists = new Map<string, RelayListEntry>();\n for (const pubkey of pubkeys) {\n const entry = toRelayListEntry(await identity.getRelays(pubkey));\n // Someone who has not said where they write is read from, and publishes to, the servers this shell writes to.\n lists.set(pubkey, entry.write.length === 0 ? withShellWrites(entry, deps.tiers) : entry);\n }\n return lists;\n },\n async signEvent(template: EventTemplate): Promise<NostrEvent> {\n const signer = deps.auth.getSigner();\n if (!signer?.signEvent) throw new Error('denied:read-only');\n return signer.signEvent(template);\n },\n verifyEvent: (event) => verifyEvent(event),\n });\n return createOutboxService({ router: acceptAnyRelay(router) });\n}\n\n/**\n * Put the outbox service's publishes through the consent gate.\n *\n * kehto's outbox router signs through a `signEvent` that is not told which\n * window asked, so the gate cannot sit at the signer as it does for `relay`.\n * It sits in front of the service instead, where the window is still known:\n * the publish reaches the router only after the gate resolves.\n *\n * @param outbox - kehto's outbox service.\n * @param consent - The signing consent gate.\n * @returns The same service with `outbox.publish` gated.\n * @example\n * ```ts\n * registry.outbox = gateOutboxPublish(createOutboxService({ router }), consent);\n * ```\n */\nfunction gateOutboxPublish(outbox: ServiceHandler, consent: SigningConsent): ServiceHandler {\n return {\n ...outbox,\n handleMessage(windowId, message, send) {\n if (message.type !== 'outbox.publish') {\n outbox.handleMessage(windowId, message, send);\n return;\n }\n const { id, event } = message as { id?: string; event?: SigningTemplate | null };\n consent(windowId, event ?? {}).then(\n () => outbox.handleMessage(windowId, message, send),\n (error: Error) => {\n const refusal = { type: 'outbox.publish.result', id: id ?? '', ok: false, error: error.message };\n send(refusal);\n },\n );\n },\n };\n}\n\n/**\n * Register kehto's reference services over the shell's applesauce layer.\n *\n * `relay`, `identity`, `theme`, `notify`, `link`, `resource`, `dm` and `outbox`\n * are wired; every network path goes through the one pool, every resource\n * fetch through the bridge registry's SSRF policy, links open only over\n * `https:` and `mailto:`, notifications surface through the host, and outbox\n * publishes pass the consent gate before they are signed.\n *\n * @param deps - Pool, tiers, store, auth, consent gate, host, registries and identity resolver.\n * @returns The service registry and the theme and dm handles.\n * @example\n * ```ts\n * const services = createKernlServices(deps);\n * const adapter: ShellAdapter = { ..., services: services.registry };\n * ```\n */\nexport function createKernlServices(deps: KernlServiceDeps): KernlServices {\n const identity = deps.identity ?? createIdentityProviders(deps.eventStore, deps.pool, deps.tiers);\n const theme = createThemeService(deps.theme ? { initialTheme: deps.theme } : {});\n const composite = deps.messaging.composite();\n const dm = createDmService({ adapter: deps.profiles ? labelConversations(composite, deps.profiles) : composite });\n const resolve = createBridgeResourceResolver(deps.bridges);\n\n const registry: ServiceRegistry = {\n relay: createRelayPoolService(createAppletRelayBackend(deps.pool, deps.tiers)),\n identity: createIdentityService({ getSigner: () => identitySigner(deps.auth), ...identity }),\n theme: theme.handler,\n notify: createNotifyService({\n present: ({ windowId, message }) => deps.host.notify({ title: message.title, windowId, tone: 'info', ...(message.body ? { body: message.body } : {}) }),\n }),\n link: createLinkService({\n allowedProtocols: LINK_PROTOCOLS,\n open: ({ url }) => {\n deps.host.openLink(url.href);\n return { status: 'opened' };\n },\n }),\n resource: createResourceService({\n fetch: (url, init) => resolve(url, resourceInitFor(deps, init)),\n resolveIdentity: deps.resolveIdentity,\n }),\n dm,\n outbox: gateOutboxPublish(createOutbox(deps, identity), deps.consent),\n ...(deps.uploader ? { upload: createUploadService({ uploader: deps.uploader, uploadInfo: { rails: [{ rail: 'blossom', enabled: true }] } }) } : {}),\n };\n return { registry, theme, dm };\n}\n","import type { AccountManager } from 'applesauce-accounts';\nimport { verifyEvent } from 'applesauce-core/helpers';\nimport type { CapabilityHooks, NappletRevocation, ShellAdapter, UnroutedMessageInfo } from '@kehto/shell';\nimport type { ServiceRegistry } from '@kehto/runtime';\nimport type { RelayTier, RelayTiers } from './types.js';\nimport { createAuthHooks } from './applesauce/auth-hooks.js';\nimport type { SigningConsent } from './consent/handler.js';\nimport { createRelayPoolHooks, type ApplesaucePool } from './applesauce/relay-hooks.js';\nimport type { RuntimeFirewallHooks } from './guard/runtime-rules.js';\n\nconst TIERS: readonly string[] = ['discovery', 'apps', 'outbox', 'super'];\n\n/** What the adapter needs from the rest of the shell. */\nexport interface ShellAdapterDeps {\n readonly pool: ApplesaucePool;\n readonly tiers: RelayTiers;\n readonly accounts: AccountManager;\n /** Gates every signature made for an applet window; see `createSigningConsent`. */\n readonly consent: SigningConsent;\n readonly services: ServiceRegistry;\n readonly resolveEnvironment: NonNullable<CapabilityHooks['resolveEnvironment']>;\n readonly onNappletRevoked: (revocation: NappletRevocation) => void;\n /** Decides every port envelope before kehto's runtime sees it; see `GuardPipeline.observe`. */\n readonly filterNappletMessage: NonNullable<ShellAdapter['filterNappletMessage']>;\n /** Whether a window has focus, as the shell's window manager reports it. */\n readonly getFocusContext: (windowId: string) => { focused: boolean };\n /** The runtime firewall's persistence and event sink; see `createRuntimeFirewallHooks`. */\n readonly runtimeFirewall: RuntimeFirewallHooks;\n readonly onUnroutedMessage?: (info: UnroutedMessageInfo) => void;\n}\n\nconst UPLOAD_BACKEND = Object.freeze({ rails: Object.freeze(['blossom']) });\n\nfunction isTier(tier: string): tier is RelayTier {\n return TIERS.includes(tier);\n}\n\n/**\n * Build kehto's `ShellAdapter` from kernl's parts.\n *\n * Choices kehto left open, decided here: windows are created by the host,\n * which opens an intent's target for it, not by applets (`createWindow`\n * returns null); the `intent` domain is offered, served by kernl's router; hotkeys are\n * not forwarded; there is no worker relay, the applesauce pool is the only\n * event source; every signature made for an applet window passes the consent\n * gate; update behaviour is `banner`; event signatures are verified by\n * applesauce; every applet's environment is narrowed by the grants layer; the\n * ACL is restrictive, so an applet holds only what the grants layer wrote; and\n * every port envelope passes kernl's guard before the runtime sees it.\n *\n * @param deps - Pool, tiers, accounts, services and the shell's hooks.\n * @returns The adapter for `createShellBridge`.\n * @example\n * ```ts\n * const bridge = createShellBridge(createShellAdapter(deps));\n * ```\n */\nexport function createShellAdapter(deps: ShellAdapterDeps): ShellAdapter {\n const { tiers } = deps;\n return {\n relayPool: createRelayPoolHooks(deps.pool, tiers),\n relayConfig: {\n addRelay(tier, url) {\n if (isTier(tier)) tiers.add(tier, url);\n },\n removeRelay(tier, url) {\n if (isTier(tier)) tiers.remove(tier, url);\n },\n getRelayConfig() {\n const config = tiers.get();\n return { discovery: [...config.discovery], super: [...config.super], outbox: [...config.outbox] };\n },\n getNip66Suggestions: () => null,\n },\n windowManager: { createWindow: () => null },\n auth: createAuthHooks(deps.accounts, deps.consent),\n config: { getNappUpdateBehavior: () => 'banner' },\n hotkeys: { executeHotkeyFromForward: () => undefined },\n workerRelay: { getWorkerRelay: () => null },\n // kehto offers the upload domain only when both the service and this backend are present; kernl's uploads are Blossom (D-033).\n upload: { getUploader: () => (deps.services.upload ? UPLOAD_BACKEND : null) },\n crypto: { verifyEvent: (event) => Promise.resolve(verifyEvent(event)) },\n link: { isAvailable: () => true },\n intent: { isAvailable: () => true },\n services: deps.services,\n capabilities: { resolveEnvironment: deps.resolveEnvironment },\n onNappletRevoked: deps.onNappletRevoked,\n filterNappletMessage: deps.filterNappletMessage,\n getFocusContext: deps.getFocusContext,\n ...deps.runtimeFirewall,\n aclDefaultPolicy: 'restrictive',\n ...(deps.onUnroutedMessage ? { onUnroutedMessage: deps.onUnroutedMessage } : {}),\n };\n}\n","import type { Subscription } from 'rxjs';\nimport { originRegistry, type ShellAdapter, type ShellBridge } from '@kehto/shell';\nimport type { NappletArtifactCache } from '@kehto/nip/5d';\nimport type { AppletHandle, AppletIdentity, AppletPointer, AppletSummary, BuiltinApplet, FrameLike, Kernl, KernlHost, MountPlan, RelayTiers } from './types.js';\nimport type { ApplesaucePool } from './applesauce/relay-hooks.js';\nimport { resolveBuiltin } from './applets/builtin.js';\nimport { fetchManifestEvent, resolveApplet, type PublishedPointer, type ResolvedApplet } from './applets/resolve.js';\nimport { planMount } from './applets/plan.js';\nimport { mountApplet, type MountedApplet } from './applets/mount.js';\nimport type { GuardPipeline, WindowResolution } from './guard/pipeline.js';\nimport { applyRuntimeFirewallRules } from './guard/runtime-rules.js';\nimport type { KernlGrants } from './grants/grants.js';\nimport type { InstalledApplets } from './intents/installed.js';\n\n/** What the applet lifecycle needs from the composed shell. */\nexport interface LifecycleContext {\n readonly pool: ApplesaucePool;\n readonly tiers: RelayTiers;\n readonly adapter: ShellAdapter;\n readonly bridge: ShellBridge;\n readonly pipeline: GuardPipeline;\n readonly grants: KernlGrants;\n /** Every planned applet is installed, so others can hand it work. */\n readonly installed: InstalledApplets;\n readonly host: Pick<KernlHost, 'onRevoked'>;\n /** Live handles keyed by window id; shared with the bridge's revocation hook. */\n readonly handles: Map<string, MountedApplet>;\n readonly subscriptions: Subscription;\n readonly openCache: () => Promise<NappletArtifactCache | undefined>;\n readonly fetchBlob: (sha256: string, servers: readonly string[]) => Promise<Uint8Array>;\n /** Applets the host ships with itself. */\n readonly builtins: readonly BuiltinApplet[];\n}\n\n/** The applet half of {@link Kernl}. */\nexport type AppletLifecycle = Pick<Kernl, 'resolve' | 'install' | 'plan' | 'mount' | 'applets' | 'handleWindowMessage'>;\n\nfunction keyOf(identity: AppletIdentity): string {\n return `${identity.dTag}:${identity.hash}`;\n}\n\n/**\n * Resolve the window a window-level message came from, from the shell's own\n * registry and never from the message.\n *\n * @param handles - Live applet handles.\n * @param event - The window-level message.\n * @returns The window and its applet, or null for unregistered sources.\n * @example\n * ```ts\n * resolveWindow(handles, event)?.napplet; // 'chat'\n * ```\n */\nexport function resolveWindow(handles: ReadonlyMap<string, MountedApplet>, event: MessageEvent): WindowResolution | null {\n const windowId = event.source ? originRegistry.getWindowId(event.source as Window) : undefined;\n const handle = windowId === undefined ? undefined : handles.get(windowId);\n return windowId !== undefined && handle ? { windowId, napplet: handle.summary.identity.dTag } : null;\n}\n\n/**\n * Load a built-in applet and, the first time the user meets it, switch on the domains its host\n * vouches for. A domain this shell cannot provide is skipped, and an applet the user already has\n * a record for is left exactly as they set it.\n */\nasync function resolveShipped(context: LifecycleContext, id: string): Promise<ResolvedApplet> {\n const resolved = await resolveBuiltin(context.builtins, id);\n const { identity } = resolved.summary;\n if (context.grants.get(identity)) return resolved;\n context.grants.ensure(identity);\n const offered = context.grants.availableDomains();\n const wanted = context.builtins.find((applet) => applet.id === id)?.grants ?? [];\n for (const domain of wanted) if (offered.includes(domain)) context.grants.allowDomain(identity, domain);\n return resolved;\n}\n\n/**\n * The applet lifecycle: `resolve` fetches and verifies (or loads an applet the host ships), `plan` narrows the\n * environment under the user's grants and installs the applet, `mount` performs the NIP-5D mount order\n * and `handleWindowMessage` runs the guard in front of the bridge.\n *\n * @param context - The composed shell's parts.\n * @returns The lifecycle methods.\n * @example\n * ```ts\n * const lifecycle = createAppletLifecycle(context);\n * const summary = await lifecycle.resolve(pointer);\n * ```\n */\nexport function createAppletLifecycle(context: LifecycleContext): AppletLifecycle {\n const { handles, pipeline, bridge } = context;\n const verified = new Map<string, string>();\n let windowCounter = 0;\n const lookUp = async (pointer: PublishedPointer): Promise<ResolvedApplet> => {\n const event = await fetchManifestEvent(context.pool, context.tiers, pointer);\n const cache = await context.openCache();\n const { fetchBlob } = context;\n const relays = pointer.relays;\n return resolveApplet(cache ? { event, fetchBlob, cache, relays } : { event, fetchBlob, relays });\n };\n\n return {\n async resolve(pointer: AppletPointer): Promise<AppletSummary> {\n const resolved = pointer.kind === 'builtin' ? await resolveShipped(context, pointer.id) : await lookUp(pointer);\n verified.set(keyOf(resolved.summary.identity), resolved.indexHtml);\n return resolved.summary;\n },\n install(summary: AppletSummary) {\n if (!verified.has(keyOf(summary.identity))) throw new Error('invalid:unresolved');\n context.grants.ensure(summary.identity);\n return context.installed.install(summary);\n },\n async plan(summary: AppletSummary): Promise<MountPlan> {\n const indexHtml = verified.get(keyOf(summary.identity));\n if (indexHtml === undefined) throw new Error('invalid:unresolved');\n if (context.grants.get(summary.identity)?.blocked) throw new Error('denied:blocked');\n context.grants.ensure(summary.identity);\n context.installed.install(summary);\n windowCounter += 1;\n return planMount({ summary, indexHtml, adapter: context.adapter, guardProfile: pipeline.config.profile, windowId: `applet-${windowCounter}` });\n },\n mount(plan: MountPlan, frame: FrameLike): AppletHandle {\n applyRuntimeFirewallRules(bridge.runtime.firewallState, pipeline.config, plan.summary.identity.dTag);\n const handle = mountApplet(plan, frame, {\n bridge,\n originRegistry,\n guard: pipeline,\n onRevoked: (windowId, reason) => context.host.onRevoked(windowId, reason),\n });\n handles.set(plan.windowId, handle);\n context.subscriptions.add(handle.status$.subscribe((status) => {\n if (status === 'closed' || status === 'revoked') handles.delete(plan.windowId);\n }));\n return handle;\n },\n applets: () => [...handles.values()],\n handleWindowMessage(event) {\n pipeline.handleWindowMessage(event, (message) => resolveWindow(handles, message), (message) => bridge.handleMessage(message));\n },\n };\n}\n","import { BehaviorSubject, map, of, Subject, Subscription, switchMap } from 'rxjs';\nimport { EventStore } from 'applesauce-core';\nimport { RelayPool } from 'applesauce-relay';\nimport type { AccountManager, IAccount } from 'applesauce-accounts';\nimport type { ISigner } from 'applesauce-signers';\nimport type { MessagingRegistry } from '@kernlize/messaging';\nimport { buildShellCapabilities, createShellBridge, type ShellAdapter, type ShellBridge } from '@kehto/shell';\nimport { createGuardConfig, describeMitigations, type GuardEvent } from '@kernlize/guard';\nimport type { AppletIdentity, GuardFacade, Kernl, KernlOptions, RelayTiers, Session } from './types.js';\nimport { createKernlAccounts } from './applesauce/accounts.js';\nimport { isReadOnlyAccount } from './applesauce/auth-hooks.js';\nimport type { ProfileCard, Profiles } from './profiles/profiles.js';\nimport { createKernlNetwork } from './kernl-network.js';\nimport { askUploadConsent, createBlossomUploader } from './files/uploader.js';\nimport type { AccountMailboxes } from './relays/mailboxes.js';\nimport { createRelayTiers } from './relays/tiers.js';\nimport { decodePointer } from './applets/pointer.js';\nimport { defaultFetchBlob, openDefaultArtifactCache } from './applets/resolve.js';\nimport type { MountedApplet } from './applets/mount.js';\nimport { createGuardPipeline, type GuardPipeline } from './guard/pipeline.js';\nimport { applyRuntimeFirewallProfile, applyRuntimeFirewallRules, createRuntimeFirewallHooks } from './guard/runtime-rules.js';\nimport { createEnvironmentResolver, createGrants, type KernlGrants } from './grants/grants.js';\nimport { createConsentHandler, createSigningConsent, lookupReplaceable } from './consent/handler.js';\nimport { abbreviate } from './consent/describe-change.js';\nimport { createDefaultMessaging } from './messaging/default-registry.js';\nimport { messagingSigner } from './messaging/availability.js';\nimport { createPrivateMessagesBackend } from './messaging/private-backend.js';\nimport { createLegacyMessagesBackend } from './messaging/legacy-backend.js';\nimport { createRatchetMessagesBackend } from './messaging/ratchet-backend.js';\nimport { createGroupMessagesBackend } from './messaging/group-backend.js';\nimport { createDefaultBridges } from './bridges/default-registry.js';\nimport { createKernlServices, isTheme } from './kernl-services.js';\nimport { createShellAdapter } from './kernl-adapter.js';\nimport { createAppletLifecycle } from './kernl-lifecycle.js';\nimport { createKernlIntents } from './kernl-intents.js';\nimport { loadCatalog, streamCatalog } from './catalog/fetch.js';\n\n/**\n * Describe an account as a session the UI can show.\n *\n * @param account - An applesauce account.\n * @returns The session; `readOnly` when the account cannot sign.\n * @example\n * ```ts\n * toSession(ReadonlyAccount.fromPubkey(pubkey)).readOnly; // true\n * ```\n */\nexport function toSession(account: IAccount, card?: ProfileCard): Session {\n const metadata = account.metadata as { name?: unknown } | undefined;\n const named = typeof metadata?.name === 'string' ? metadata.name : account.name;\n const label = named ?? (card?.found ? card.name : abbreviate(account.pubkey));\n return { accountId: account.id, pubkey: account.pubkey, label, readOnly: isReadOnlyAccount(account) };\n}\n\ninterface ShellState {\n readonly pipeline: GuardPipeline;\n readonly bridge: ShellBridge;\n readonly handles: ReadonlyMap<string, MountedApplet>;\n readonly accounts: AccountManager;\n readonly session$: BehaviorSubject<Session | null>;\n readonly profiles: Profiles;\n readonly mailboxes: AccountMailboxes;\n readonly tiers: RelayTiers;\n}\n\n/** Keep the runtime firewall on the guard's profile and the session on the active account. */\nfunction followShellState({ pipeline, bridge, handles, accounts, session$, profiles, mailboxes, tiers }: ShellState): Subscription {\n const subscriptions = new Subscription();\n subscriptions.add(pipeline.profile$.subscribe(() => {\n applyRuntimeFirewallProfile(bridge.runtime.firewallState, pipeline.config);\n for (const handle of handles.values()) applyRuntimeFirewallRules(bridge.runtime.firewallState, pipeline.config, handle.summary.identity.dTag);\n }));\n subscriptions.add(accounts.active$.subscribe((account) => bridge.publishIdentityChanged(account?.pubkey ?? '')));\n // The session's label follows the account's published name once it arrives.\n const sessions = accounts.active$.pipe(switchMap((account) => (account ? profiles.card$(account.pubkey).pipe(map((card) => toSession(account, card))) : of(null))));\n subscriptions.add(sessions.subscribe(session$));\n // Where the account says it publishes is where the shell publishes for it (NIP-65, D-029).\n subscriptions.add(mailboxes.state$.subscribe((state) => {\n if (state.status === 'found') tiers.set('outbox', state.mailboxes.outboxes);\n }));\n return subscriptions;\n}\n\n/** Signing in and out. The session itself is a getter on the shell, so spreading this never copies a stale value. */\nfunction createSignIn(accounts: AccountManager): Pick<Kernl, 'login' | 'logout'> {\n return {\n async login(account) {\n if (!accounts.getAccount(account.id)) accounts.addAccount(account);\n accounts.setActive(account);\n return toSession(account);\n },\n async logout() {\n accounts.clearActive();\n },\n };\n}\n\nfunction createGuardFacade(pipeline: GuardPipeline, events$: Subject<GuardEvent>): GuardFacade {\n return {\n get config() {\n return pipeline.config;\n },\n profile$: pipeline.profile$,\n setProfile: (profile) => pipeline.setProfile(profile),\n events$: events$.asObservable(),\n mitigations: () => describeMitigations(pipeline.config),\n release: (windowId) => pipeline.release(windowId),\n };\n}\n\ninterface MessagingParts {\n readonly eventStore: EventStore;\n readonly pool: RelayPool;\n readonly tiers: RelayTiers;\n readonly accounts: AccountManager;\n}\n\n/** kernl's account-signer backends for `private`, `legacy` and `ratchet`, unless the host supplied its own. */\nfunction createAccountMessaging(options: KernlOptions, parts: MessagingParts): MessagingRegistry {\n const signer = (): ISigner | undefined => messagingSigner(parts.accounts.active);\n const deps = {\n store: parts.eventStore,\n pool: parts.pool,\n tiers: parts.tiers,\n signer,\n selfPubkey: () => parts.accounts.active?.pubkey,\n accountChanges: parts.accounts.active$,\n };\n const { host } = options;\n return createDefaultMessaging({\n storage: host.storage,\n signer,\n ...(host.chooseReply ? { askReply: host.chooseReply.bind(host) } : {}),\n backends: {\n private: () => createPrivateMessagesBackend(deps),\n legacy: () => createLegacyMessagesBackend(deps),\n ratchet: () => createRatchetMessagesBackend({ ...deps, storage: options.host.storage }),\n group: () => createGroupMessagesBackend({ ...deps, storage: options.host.storage }),\n ...options.messagingBackends,\n },\n });\n}\n\n/** The host's messaging and bridge registries, or kernl's defaults over the shell's parts. */\nfunction registriesFor(options: KernlOptions, parts: MessagingParts): Pick<Kernl, 'messaging' | 'bridges'> {\n const { host } = options;\n return {\n messaging: options.messaging ?? createAccountMessaging(options, parts),\n // host.openLink asks before leaving kernl, so every hand-off is confirmed by the user (D-010).\n bridges: options.bridges ?? createDefaultBridges({ handoff: (uri) => host.openLink(uri), ...(options.torrent ? { torrent: options.torrent } : {}) }),\n };\n}\n\ninterface ShellParts {\n readonly handles: ReadonlyMap<string, MountedApplet>;\n readonly subscriptions: Subscription;\n readonly destroyed$: Subject<void>;\n readonly network: { readonly directory: { stop(): void }; readonly eventCache: { close(): Promise<void> } };\n readonly intents: { close(): void };\n readonly dm: { dispose(): void };\n readonly bridge: ShellBridge;\n /** Closed only when the shell created it. */\n readonly messaging?: MessagingRegistry;\n readonly pool?: RelayPool;\n}\n\n/** Close every applet, then everything the shell opened, the parts it was handed excepted. */\nfunction tearDown(parts: ShellParts): void {\n for (const handle of [...parts.handles.values()]) handle.close();\n parts.subscriptions.unsubscribe();\n parts.destroyed$.next();\n parts.network.directory.stop();\n void parts.network.eventCache.close();\n parts.intents.close();\n parts.dm.dispose();\n parts.bridge.destroy();\n parts.messaging?.close();\n parts.pool?.close();\n}\n\n/**\n * Compose the shell: one `EventStore`, one `RelayPool`, one `AccountManager`,\n * the relay tiers, the guard pipeline, the grants layer, the messaging and\n * bridge registries, kehto's services (intents included) and\n * `createShellBridge`, the applet store's catalogue, plus the applet lifecycle\n * `decodePointer` → `resolve` → `plan` → `mount`.\n *\n * Anything the host passes in `options` is used as is; anything missing is\n * created with kernl's defaults. The host wires `handleWindowMessage` to the\n * window once and supplies the frames; everything else is reached through\n * {@link KernlHost}.\n *\n * @param options - Host hooks and optional pre-built parts.\n * @returns The shell.\n * @example\n * ```ts\n * const kernl = createKernl({ host });\n * window.addEventListener('message', (event) => kernl.handleWindowMessage(event));\n * const summary = await kernl.resolve(kernl.decodePointer(address));\n * const handle = kernl.mount(await kernl.plan(summary), iframe);\n * ```\n */\nexport function createKernl(options: KernlOptions): Kernl {\n const { host } = options;\n const ownsPool = !options.pool;\n const ownsMessaging = !options.messaging;\n const eventStore = options.eventStore ?? new EventStore();\n const pool = options.pool ?? new RelayPool();\n const accounts = options.accounts ?? createKernlAccounts(host.storage);\n const tiers = createRelayTiers(host.storage, options.relays ?? {});\n const { messaging, bridges } = registriesFor(options, { eventStore, pool, tiers, accounts });\n\n const handles = new Map<string, MountedApplet>();\n const guardEvents$ = new Subject<GuardEvent>();\n const session$ = new BehaviorSubject<Session | null>(null);\n const destroyed$ = new Subject<void>();\n const subscriptions = new Subscription();\n let grants: KernlGrants;\n\n const pipeline = createGuardPipeline({\n config: createGuardConfig(options.guard?.profile ?? 'strict'),\n ...(host.now ? { now: host.now.bind(host) } : {}),\n onEvent: (event) => guardEvents$.next(event),\n onQuarantine: (windowId) => {\n handles.get(windowId)?.revoked('quarantine');\n bridge.revokeNapplet(windowId, 'host');\n },\n getVisibility: (windowId) => host.getVisibility(windowId),\n onRelease: (windowId) => bridge.releaseDeferred(windowId),\n });\n\n const identityOf = (windowId: string): AppletIdentity | undefined => handles.get(windowId)?.summary.identity;\n const { eventCache, replaceableLoader, profiles, directory, mailboxes, files, signer } = createKernlNetwork(options, { eventStore, pool, tiers, accounts, destroyed$ });\n const lookupBefore = lookupReplaceable(eventStore, {\n loader: replaceableLoader,\n relays: () => [...tiers.get().outbox, ...tiers.get().discovery],\n });\n const consent = createSigningConsent({ host, lookupBefore, resolveApplet: identityOf, pubkey: () => accounts.active?.pubkey });\n const services = createKernlServices({\n pool,\n tiers,\n eventStore,\n auth: { getSigner: () => adapter.auth.getSigner(), getUserPubkey: () => adapter.auth.getUserPubkey() },\n consent,\n host,\n bridges,\n messaging,\n profiles,\n uploader: createBlossomUploader({\n servers: () => files.current(),\n signer,\n ask: (windowId, details) => askUploadConsent(host, identityOf(windowId), details),\n }),\n ...(isTheme(options.theme) ? { theme: options.theme } : {}),\n resolveIdentity(windowId) {\n const identity = identityOf(windowId);\n return identity ? { dTag: identity.dTag, aggregateHash: identity.hash } : null;\n },\n });\n\n const intents = createKernlIntents({ host, pool, tiers, accounts, handles, ...(options.intentRetry ? { retry: options.intentRetry } : {}) });\n services.registry.intent = intents.handler;\n const adapter: ShellAdapter = createShellAdapter({\n pool,\n tiers,\n accounts,\n consent,\n services: services.registry,\n resolveEnvironment: (identity, available) => createEnvironmentResolver(grants)(identity, available),\n onNappletRevoked: ({ windowId, reason }) => handles.get(windowId)?.revoked(reason),\n filterNappletMessage: (windowId, message) => pipeline.observe(windowId, identityOf(windowId)?.dTag ?? 'unknown', message),\n getFocusContext: (windowId) => ({ focused: pipeline.getVisibility(windowId).focused }),\n runtimeFirewall: createRuntimeFirewallHooks({\n storage: host.storage,\n onEvent: (event) => guardEvents$.next(event),\n ...(host.now ? { now: host.now.bind(host) } : {}),\n }),\n });\n const bridge = createShellBridge(adapter);\n grants = createGrants({ acl: bridge.runtime.aclState, storage: host.storage, availableDomains: () => buildShellCapabilities(adapter).domains });\n bridge.registerConsentHandler(createConsentHandler(host, lookupBefore, identityOf));\n\n subscriptions.add(followShellState({ pipeline, bridge, handles, accounts, session$, profiles, mailboxes, tiers }));\n\n const lifecycle = createAppletLifecycle({\n pool,\n tiers,\n adapter,\n bridge,\n pipeline,\n grants,\n installed: intents.installed,\n host,\n handles,\n subscriptions,\n openCache: options.artifactCache ?? openDefaultArtifactCache,\n fetchBlob: host.fetchBlob ? host.fetchBlob.bind(host) : defaultFetchBlob,\n builtins: options.builtins ?? [],\n });\n\n return {\n accounts,\n eventStore,\n pool,\n bridge,\n guard: createGuardFacade(pipeline, guardEvents$),\n grants,\n relays: tiers,\n messaging,\n bridges,\n catalog: {\n load: (loadOptions) => loadCatalog(pool, tiers, { cache: eventCache.cacheRequest, store: eventStore, ...loadOptions }),\n stream: (streamOptions) => streamCatalog(pool, tiers, { cache: eventCache.cacheRequest, store: eventStore, ...streamOptions }),\n },\n profiles,\n mailboxes,\n files,\n directory,\n intents: intents.intents,\n session$,\n get session() {\n return session$.value;\n },\n ...createSignIn(accounts),\n decodePointer,\n ...lifecycle,\n destroy: () =>\n tearDown({ handles, subscriptions, destroyed$, network: { directory, eventCache }, intents, dm: services.dm, bridge, ...(ownsMessaging ? { messaging } : {}), ...(ownsPool ? { pool } : {}) }),\n };\n}\n","import { Subscription } from 'rxjs';\nimport type { AccountManager, IAccount } from 'applesauce-accounts';\nimport type { ServiceHandler, ServiceRuntimeContext } from '@kehto/runtime';\nimport { originRegistry } from '@kehto/shell';\nimport { createIntentService } from '@kehto/services';\nimport type { EventTemplate, NostrEvent } from '@napplet/core';\nimport type { Intents, KernlHost, RelayTiers } from './types.js';\nimport type { ApplesaucePool } from './applesauce/relay-hooks.js';\nimport { isReadOnlyAccount } from './applesauce/auth-hooks.js';\nimport type { MountedApplet } from './applets/mount.js';\nimport { createHandlerDefaults, type PreferenceSigner } from './intents/defaults.js';\nimport { createIntentDelivery } from './intents/delivery.js';\nimport { createInstalledApplets, type InstalledApplets } from './intents/installed.js';\nimport { createIntentRouter } from './intents/router.js';\n\n/** What {@link createKernlIntents} needs from the composed shell. */\nexport interface KernlIntentDeps {\n readonly host: KernlHost;\n readonly pool: ApplesaucePool;\n readonly tiers: RelayTiers;\n readonly accounts: AccountManager;\n /** Live applet handles by window id; the source of every sender identity. */\n readonly handles: ReadonlyMap<string, MountedApplet>;\n readonly retry?: { readonly intervalMs: number; readonly attempts: number };\n}\n\n/** The intent service for kehto's registry, the user-facing surface and the installed set the lifecycle writes. */\nexport interface KernlIntents {\n readonly handler: ServiceHandler;\n readonly intents: Intents;\n readonly installed: InstalledApplets;\n close(): void;\n}\n\nconst FAILURES: Readonly<Record<string, string>> = {\n 'unavailable:delivery': 'It needs \"opening other applets\" switched on in its grants to receive requests from other applets.',\n 'unavailable:window': 'It could not be opened.',\n 'unavailable:handler': 'It is no longer installed.',\n};\n\n/** What the user is told when the host itself failed while opening the handler. */\nconst UNREACHABLE = 'It could not be reached.';\n\nfunction signerOf(account: IAccount | undefined): PreferenceSigner | undefined {\n if (!account || isReadOnlyAccount(account)) return undefined;\n return (template: EventTemplate) => account.signEvent(template) as Promise<NostrEvent>;\n}\n\n/**\n * Keep the runtime context kehto hands the intent service, so delivery can\n * use the runtime's recipient-checked send rather than a raw port.\n */\nfunction withContext(inner: ServiceHandler, hold: (context: ServiceRuntimeContext | undefined) => void): ServiceHandler {\n return {\n ...inner,\n onRegistered(context) {\n hold(context);\n inner.onRegistered?.(context);\n },\n onUnregistered() {\n hold(undefined);\n inner.onUnregistered?.();\n },\n };\n}\n\n/**\n * Compose NAP-INTENT for the shell: the installed set, the user's handler\n * defaults, kernl's router over kehto's catalogue resolver, delivery through\n * the host's window opener, and kehto's `createIntentService`.\n *\n * The sender of every invocation is the verified catalogue id of the window\n * it came from, looked up from the shell's own handles and never from the\n * message. The user's published preferences are re-read whenever the active\n * account changes. A delivery that fails after acceptance is reported to the\n * user, since the source has already been told yes.\n *\n * @param deps - Host, pool, tiers, accounts and live handles.\n * @returns The service handler, the facade and the installed set.\n * @example\n * ```ts\n * const intents = createKernlIntents({ host, pool, tiers, accounts, handles });\n * services.registry.intent = intents.handler;\n * ```\n */\nexport function createKernlIntents(deps: KernlIntentDeps): KernlIntents {\n const { host, handles } = deps;\n const installed = createInstalledApplets(host.storage, host.now ? host.now.bind(host) : Date.now);\n const defaults = createHandlerDefaults({\n storage: host.storage,\n pool: deps.pool,\n tiers: deps.tiers,\n pubkey: () => deps.accounts.active?.pubkey,\n signer: () => signerOf(deps.accounts.active),\n });\n let context: ServiceRuntimeContext | undefined;\n const titleOf = (catalogId: string): string => installed.get(catalogId)?.title ?? 'An applet';\n\n const deliver = createIntentDelivery({\n installed,\n findWindow: (catalogId) => [...handles.values()].find((handle) => handle.summary.manifest.catalogId === catalogId)?.windowId,\n openApplet: async (address) => host.openApplet?.(address),\n ...(host.focusApplet ? { focus: host.focusApplet.bind(host) } : {}),\n // kehto's ACL gives `intent.deliver` no recipient capability, so the runtime's recipient-checked\n // send refuses it. Like kehto's own Paja host, the delivery goes over the target's bound port,\n // and only to a live session that holds the receiving grant (DECISIONS.md D-026).\n send: (windowId, message) => context?.hasCapability(windowId, 'intent:read') === true && originRegistry.postToNapplet(windowId, message),\n ...(deps.retry ? { retry: deps.retry } : {}),\n });\n\n const router = createIntentRouter({\n installed,\n defaults,\n ...(host.chooseHandler ? { choose: host.chooseHandler.bind(host) } : {}),\n describeSender: titleOf,\n deliver: (params) =>\n deliver(params).catch((error: Error) => {\n host.notify({ title: `${titleOf(params.handler)} could not take the request`, body: FAILURES[error.message] ?? UNREACHABLE, tone: 'warning' });\n throw error;\n }),\n });\n\n const service = createIntentService({ resolver: router, resolveSender: (windowId) => handles.get(windowId)?.summary.manifest.catalogId });\n const subscriptions = new Subscription();\n subscriptions.add(installed.changes$.subscribe((list) => {\n for (const slug of new Set(list.flatMap((applet) => applet.contracts.map((contract) => contract.slug)))) router.notifyChanged(slug);\n }));\n subscriptions.add(defaults.changes$.subscribe((archetype) => router.notifyChanged(archetype)));\n subscriptions.add(deps.accounts.active$.subscribe(() => void defaults.load()));\n\n return {\n handler: withContext(service, (next) => {\n context = next;\n }),\n installed,\n intents: {\n installed$: installed.changes$,\n installed: () => installed.list(),\n uninstall: (catalogId) => installed.remove(catalogId),\n defaults,\n },\n close: () => subscriptions.unsubscribe(),\n };\n}\n","import { lastValueFrom, Subject, takeUntil, timer, toArray, type Observable } from 'rxjs';\nimport { verifyEvent } from 'applesauce-core/helpers';\nimport type { EventTemplate, NostrEvent } from '@napplet/core';\nimport type { RelayTiers, StorageLike } from '../types.js';\nimport { asFilters, type ApplesaucePool } from '../applesauce/relay-hooks.js';\nimport { createNamespacedStore } from '../persistence/store.js';\nimport { HANDLER_PREFERENCES_KIND, parseHandlerPreferences, preferenceTemplate, type HandlerPreferences } from './preferences.js';\n\n/** Signs the shell's own preference events. Present only while the active account can sign. */\nexport type PreferenceSigner = (template: EventTemplate) => Promise<NostrEvent>;\n\n/** What {@link createHandlerDefaults} needs. */\nexport interface HandlerDefaultsOptions {\n readonly storage: StorageLike;\n readonly pool: ApplesaucePool;\n readonly tiers: RelayTiers;\n /** The signed-in account's public key, if any. */\n readonly pubkey: () => string | undefined;\n readonly signer: () => PreferenceSigner | undefined;\n /** Seconds since the epoch. */\n readonly now?: () => number;\n}\n\n/** The user's handler choices: what this device remembers, and what their account published. */\nexport interface HandlerDefaults {\n /** This device's default for an archetype. */\n get(archetype: string): string | undefined;\n /** Every default this device remembers, by archetype. */\n all(): Readonly<Record<string, string>>;\n /**\n * Remember a default, or forget it with `undefined`. With `sync` on and an\n * account that can sign, the choice is also published as the user's\n * handler preference for the archetype.\n */\n set(archetype: string, catalogId: string | undefined): Promise<void>;\n /** The account's published preferences for an archetype, once loaded. */\n synced(archetype: string): HandlerPreferences | undefined;\n /** Read the signed-in account's published preferences from its relays. */\n load(): Promise<void>;\n /** Whether choices are published to the account. Off until the user turns it on. */\n readonly sync: boolean;\n setSync(on: boolean): void;\n /** The archetype whose defaults or published preferences just changed. */\n readonly changes$: Observable<string>;\n}\n\nconst DEFAULTS_KEY = 'intent-defaults:v1';\n/** Published preferences that have not arrived after this long are read on the next sign-in. */\nconst LOAD_TIMEOUT_MS = 8000;\nconst SYNC_KEY = 'intent-sync:v1';\n\n/**\n * The relays a preference event is read from and written to: the user's\n * outbox, then the public relays (the spec's NIP-65 write relays, as the shell\n * knows them).\n *\n * @param tiers - The shell's relay tiers.\n * @returns Deduplicated relay URLs.\n * @example\n * ```ts\n * preferenceRelays(tiers); // ['wss://relay.mine', 'wss://relay.damus.io', …]\n * ```\n */\nexport function preferenceRelays(tiers: RelayTiers): readonly string[] {\n const { outbox, super: shared } = tiers.get();\n return [...new Set([...outbox, ...shared])];\n}\n\nfunction newestPerArchetype(events: readonly NostrEvent[], pubkey: string): Map<string, NostrEvent> {\n const newest = new Map<string, NostrEvent>();\n for (const event of events) {\n // The spec's rule: apply only events whose signature verifies and whose author is the user.\n if (event.kind !== HANDLER_PREFERENCES_KIND || event.pubkey !== pubkey || !verifyEvent(event)) continue;\n const archetype = event.tags.find((tag) => tag[0] === 'd')?.[1] ?? '';\n const current = newest.get(archetype);\n if (archetype && (!current || event.created_at > current.created_at)) newest.set(archetype, event);\n }\n return newest;\n}\n\n/**\n * Handler defaults over local storage and the account's kind-31129 events.\n *\n * Local defaults are kept at `kernl:intent-defaults:v1` and always win, as the\n * spec allows a shell's own preferences to select without prompting. Published\n * preferences are read for the signed-in account and used to rank and\n * pre-select handlers. Publishing is opt-in (`kernl:intent-sync:v1`), because\n * the archetype a user set preferences for is public.\n *\n * @param options - Storage, pool, tiers and the active account's key and signer.\n * @returns The defaults.\n * @example\n * ```ts\n * const defaults = createHandlerDefaults({ storage, pool, tiers, pubkey, signer });\n * await defaults.set('profile', 'nip5d:35129:…:profile-viewer');\n * ```\n */\nexport function createHandlerDefaults(options: HandlerDefaultsOptions): HandlerDefaults {\n const store = createNamespacedStore(options.storage, 'kernl');\n const local = new Map(Object.entries(store.getJson<Record<string, string>>(DEFAULTS_KEY, {})));\n const published = new Map<string, NostrEvent>();\n const changes$ = new Subject<string>();\n const now = options.now ?? (() => Math.floor(Date.now() / 1000));\n let sync = store.getJson<boolean>(SYNC_KEY, false) === true;\n let loadedFor: string | undefined;\n\n async function publish(archetype: string, catalogId: string): Promise<void> {\n const sign = options.signer();\n const template = preferenceTemplate(published.get(archetype), archetype, catalogId, now());\n if (!sign || !template) return;\n const event = await sign(template);\n published.set(archetype, event);\n await options.pool.publish([...preferenceRelays(options.tiers)], event).catch(() => undefined);\n }\n\n return {\n get: (archetype) => local.get(archetype),\n all: () => Object.freeze(Object.fromEntries(local)),\n async set(archetype, catalogId) {\n if (catalogId === undefined) local.delete(archetype);\n else local.set(archetype, catalogId);\n store.setJson(DEFAULTS_KEY, Object.fromEntries(local));\n changes$.next(archetype);\n if (sync && catalogId !== undefined) await publish(archetype, catalogId);\n },\n synced: (archetype) => {\n const event = published.get(archetype);\n return event ? parseHandlerPreferences(event) : undefined;\n },\n async load() {\n const pubkey = options.pubkey();\n if (pubkey !== loadedFor) published.clear();\n loadedFor = pubkey;\n if (!pubkey) return;\n const request = options.pool.request([...preferenceRelays(options.tiers)], asFilters([{ kinds: [HANDLER_PREFERENCES_KIND], authors: [pubkey] }]));\n const events = await lastValueFrom(request.pipe(takeUntil(timer(LOAD_TIMEOUT_MS)), toArray()), { defaultValue: [] }).catch(() => []);\n for (const [archetype, event] of newestPerArchetype(events, pubkey)) {\n published.set(archetype, event);\n changes$.next(archetype);\n }\n },\n get sync() {\n return sync;\n },\n setSync(on) {\n sync = on;\n store.setJson(SYNC_KEY, on);\n },\n changes$: changes$.asObservable(),\n };\n}\n","import type { EventTemplate, NostrEvent } from '@napplet/core';\n\n/**\n * The addressable kind that records a user's preferred handlers, one event\n * per archetype (\"Napplet Handler Preferences\", kind 31129).\n *\n * @example\n * ```ts\n * pool.request(relays, [{ kinds: [HANDLER_PREFERENCES_KIND], authors: [pubkey] }]);\n * ```\n */\nexport const HANDLER_PREFERENCES_KIND = 31129;\n\n/** The public entries of one kind-31129 event. Private entries in `content` are kept, not read. */\nexport interface HandlerPreferences {\n readonly archetype: string;\n /** Archetype-wide `a` and `e` references, in tag order. */\n readonly handlers: readonly string[];\n /** Intent-specific `i` references by convention identity, in tag order. */\n readonly intents: Readonly<Record<string, readonly string[]>>;\n}\n\nconst HEX_64 = /^[0-9a-f]{64}$/;\nconst NAMED = /^35129:([0-9a-f]{64}):(.+)$/s;\nconst ROOT = /^15129:([0-9a-f]{64}):$/;\nconst CONVENTION = /^napplet:([a-z0-9][a-z0-9-]*)\\/([a-z0-9][a-z0-9-]*)$/;\n\n/**\n * kehto's catalogue id for a preference reference: a named or root\n * coordinate, or a snapshot id. kehto keys named applets by publisher, kind\n * and `d`, roots by publisher and kind, snapshots by event id.\n *\n * @param ref - `35129:<pubkey>:<d>`, `15129:<pubkey>:` or a 64-hex snapshot id.\n * @returns The catalogue id, or undefined for anything else.\n * @example\n * ```ts\n * catalogIdForRef(`35129:${pubkey}:notepad`); // `nip5d:35129:${pubkey}:notepad`\n * ```\n */\nexport function catalogIdForRef(ref: string): string | undefined {\n if (HEX_64.test(ref)) return `nip5d:5129:${ref}`;\n const named = NAMED.exec(ref);\n if (named) return `nip5d:35129:${named[1] as string}:${named[2] as string}`;\n const root = ROOT.exec(ref);\n return root ? `nip5d:15129:${root[1] as string}` : undefined;\n}\n\n/**\n * The preference reference for a catalogue id; the inverse of {@link catalogIdForRef}.\n *\n * @param catalogId - A kehto catalogue id.\n * @returns The coordinate or snapshot id, or undefined when the id is not a napplet's.\n * @example\n * ```ts\n * refForCatalogId(`nip5d:15129:${pubkey}`); // `15129:${pubkey}:`\n * ```\n */\nexport function refForCatalogId(catalogId: string): string | undefined {\n const [prefix, kind, first = '', ...rest] = catalogId.split(':');\n if (prefix !== 'nip5d') return undefined;\n if (kind === '5129' && HEX_64.test(first)) return first;\n if (kind === '15129' && HEX_64.test(first) && rest.length === 0) return `15129:${first}:`;\n return kind === '35129' && HEX_64.test(first) && rest.length > 0 ? `35129:${first}:${rest.join(':')}` : undefined;\n}\n\nfunction tagRef(tag: readonly string[]): string | undefined {\n const value = tag[1];\n if (typeof value !== 'string') return undefined;\n if (tag[0] === 'a') return NAMED.test(value) || ROOT.test(value) ? value : undefined;\n return tag[0] === 'e' && HEX_64.test(value) ? value : undefined;\n}\n\nfunction intentEntry(tag: readonly string[], archetype: string): readonly [string, string] | undefined {\n const [, convention, ref] = tag;\n if (tag[0] !== 'i' || typeof convention !== 'string' || typeof ref !== 'string') return undefined;\n if (CONVENTION.exec(convention)?.[1] !== archetype) return undefined;\n return catalogIdForRef(ref) ? [convention, ref] : undefined;\n}\n\n/**\n * Read the public entries of a handler-preferences event.\n *\n * Unknown tags and malformed entries are ignored without discarding the\n * event. An `i` entry counts only when its convention is queryless,\n * fragment-free and names the event's archetype.\n *\n * @param event - A kind-31129 event, already verified as the user's.\n * @returns The preferences, or undefined when the event is not one.\n * @example\n * ```ts\n * parseHandlerPreferences(event)?.handlers; // ['35129:…:notepad']\n * ```\n */\nexport function parseHandlerPreferences(event: NostrEvent): HandlerPreferences | undefined {\n const archetype = event.tags.find((tag) => tag[0] === 'd')?.[1];\n if (event.kind !== HANDLER_PREFERENCES_KIND || !archetype) return undefined;\n const handlers: string[] = [];\n const intents: Record<string, string[]> = {};\n for (const tag of event.tags) {\n const ref = tagRef(tag);\n if (ref && !handlers.includes(ref)) handlers.push(ref);\n const entry = intentEntry(tag, archetype);\n if (entry) (intents[entry[0]] ??= []).push(entry[1]);\n }\n return Object.freeze({ archetype, handlers: Object.freeze(handlers), intents: Object.freeze(intents) });\n}\n\n/**\n * Catalogue ids the user prefers for one convention: intent-specific entries\n * when any match, otherwise the archetype-wide ones.\n *\n * @param preferences - The user's preferences for the convention's archetype.\n * @param convention - The requested convention identity.\n * @returns Catalogue ids in preference order.\n * @example\n * ```ts\n * preferredHandlers(preferences, 'napplet:profile/edit'); // ['nip5d:35129:…:profile-editor']\n * ```\n */\nexport function preferredHandlers(preferences: HandlerPreferences | undefined, convention: string): readonly string[] {\n if (!preferences) return [];\n const specific = preferences.intents[convention] ?? [];\n const refs = specific.length > 0 ? specific : preferences.handlers;\n return refs.map(catalogIdForRef).filter((id): id is string => id !== undefined);\n}\n\n/**\n * The next version of the user's preferences for an archetype, with one\n * handler moved to the front of the archetype-wide entries.\n *\n * Every other tag and the encrypted private entries are carried over as they\n * were, so the shell never drops a choice it could not read.\n *\n * @param previous - The current event, when there is one.\n * @param archetype - The archetype slug.\n * @param catalogId - The handler the user chose.\n * @param now - Seconds since the epoch.\n * @returns The event to sign, or undefined when the id has no reference form.\n * @example\n * ```ts\n * preferenceTemplate(current, 'profile', candidate.id, Math.floor(Date.now() / 1000));\n * ```\n */\nexport function preferenceTemplate(previous: NostrEvent | undefined, archetype: string, catalogId: string, now: number): EventTemplate | undefined {\n const ref = refForCatalogId(catalogId);\n if (!ref) return undefined;\n const kept = (previous?.tags ?? []).filter((tag) => tag[0] !== 'd' && tag[1] !== ref);\n const tag = HEX_64.test(ref) ? ['e', ref] : ['a', ref];\n return { kind: HANDLER_PREFERENCES_KIND, created_at: now, content: previous?.content ?? '', tags: [['d', archetype], tag, ...kept] };\n}\n","import type { IntentDelivery, IntentDispatchParams } from '@kehto/services';\nimport type { NappletMessage } from '@napplet/core';\nimport type { InstalledApplets } from './installed.js';\n\n/**\n * How often, and how many times, delivery is retried while the target's\n * session comes up: 100 ms apart for up to 15 s.\n *\n * @example\n * ```ts\n * createIntentDelivery({ ...deps, retry: DELIVERY_RETRY });\n * ```\n */\nexport const DELIVERY_RETRY = Object.freeze({ intervalMs: 100, attempts: 150 });\n\n/** What {@link createIntentDelivery} needs from the shell. */\nexport interface IntentDeliveryOptions {\n readonly installed: InstalledApplets;\n /** A window already running this catalogue id, for reuse. */\n readonly findWindow: (catalogId: string) => string | undefined;\n /** Ask the host to open the applet at this address; resolves to its window id, or undefined when it did not open. */\n readonly openApplet: (address: string) => Promise<string | undefined>;\n readonly focus?: (windowId: string) => void;\n /** The runtime's recipient-checked send; false while the target is not eligible yet. */\n readonly send: (windowId: string, message: NappletMessage) => boolean;\n readonly retry?: { readonly intervalMs: number; readonly attempts: number };\n}\n\nconst pause = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));\n\n/**\n * Deliver an accepted intent to its target.\n *\n * A running window of the handler is reused unless the request said\n * `reuse: false`, and focused unless it said `focus: false`; otherwise the\n * host opens the applet. The delivery is retried until the target's session\n * is live and holds the `intent` domain, because the runtime delivers only to\n * an eligible recipient (NAP-INTENT: \"deliver only after the target is\n * ready\"). The source window plays no part after acceptance.\n *\n * @param options - Installed set, window lookup, opener, focus and the runtime send.\n * @returns The target controller's delivery function.\n * @throws `unavailable:handler` when the handler is no longer installed, `unavailable:window` when it did not open, `unavailable:delivery` when it never became eligible.\n * @example\n * ```ts\n * const deliver = createIntentDelivery({ installed, findWindow, openApplet: host.openApplet, send });\n * await deliver(params);\n * ```\n */\nexport function createIntentDelivery(options: IntentDeliveryOptions): (params: IntentDispatchParams) => Promise<void> {\n const retry = options.retry ?? DELIVERY_RETRY;\n return async (params) => {\n const applet = options.installed.get(params.handler);\n if (!applet) throw new Error('unavailable:handler');\n const running = params.behavior?.reuse === false ? undefined : options.findWindow(params.handler);\n if (running && params.behavior?.focus !== false) options.focus?.(running);\n const windowId = running ?? (await options.openApplet(applet.address));\n if (!windowId) throw new Error('unavailable:window');\n const delivery: IntentDelivery = {\n sender: params.sender,\n archetype: params.archetype,\n action: params.action,\n convention: params.convention,\n ...(params.payload === undefined ? {} : { payload: params.payload }),\n };\n for (let attempt = 0; attempt < retry.attempts; attempt += 1) {\n if (options.send(windowId, { type: 'intent.deliver', delivery } as NappletMessage)) return;\n await pause(retry.intervalMs);\n }\n throw new Error('unavailable:delivery');\n };\n}\n","import { BehaviorSubject, type Observable } from 'rxjs';\nimport { manifestToIntentCatalogEntry, type IntentCatalogEntry } from '@kehto/services';\nimport type { AppletSummary, StorageLike } from '../types.js';\nimport { createNamespacedStore } from '../persistence/store.js';\n\n/** One advertised convention, as the verified manifest's `z` and `i` tags declared it. */\nexport interface InstalledContract {\n readonly slug: string;\n readonly convention: string;\n readonly params: readonly string[];\n}\n\n/** An applet the user has run, remembered so other applets can hand work to it. */\nexport interface InstalledApplet {\n readonly catalogId: string;\n /** What the shell resolves to open it again. */\n readonly address: string;\n readonly title: string;\n readonly publisher: string;\n readonly contracts: readonly InstalledContract[];\n readonly installedAt: number;\n}\n\n/** What installing reads from a verified applet's summary. */\nexport type InstallableApplet = Pick<AppletSummary, 'address' | 'title' | 'publisher'> & {\n readonly manifest: Pick<AppletSummary['manifest'], 'catalogId' | 'archetypes'>;\n};\n\n/** The installed set: what NAP-INTENT's `available()` and `handlers()` are built from. */\nexport interface InstalledApplets {\n list(): readonly InstalledApplet[];\n get(catalogId: string): InstalledApplet | undefined;\n /** Remember a verified applet. Re-installing replaces its contracts and keeps its place. */\n install(summary: InstallableApplet): InstalledApplet;\n remove(catalogId: string): void;\n /** The installed set as kehto's catalogue resolver reads it. */\n catalog(): readonly IntentCatalogEntry[];\n /** Replays the current list to new subscribers. */\n readonly changes$: Observable<readonly InstalledApplet[]>;\n}\n\nconst STORAGE_KEY = 'installed:v1';\n\nfunction isInstalled(value: unknown): value is InstalledApplet {\n if (typeof value !== 'object' || value === null) return false;\n const row = value as Record<string, unknown>;\n return typeof row.catalogId === 'string' && typeof row.address === 'string' && typeof row.title === 'string' && typeof row.publisher === 'string' && Array.isArray(row.contracts) && typeof row.installedAt === 'number';\n}\n\n/** A contract kehto's adapter refuses is dropped, never fatal: an odd `i` tag must not hide the applet. */\nfunction toCatalogEntry(applet: InstalledApplet): IntentCatalogEntry | undefined {\n const archetypes = applet.contracts.filter((contract) => {\n try {\n manifestToIntentCatalogEntry({ catalogId: applet.catalogId, archetypes: [{ ...contract, params: [...contract.params] }] });\n return true;\n } catch {\n return false;\n }\n });\n if (archetypes.length === 0) return undefined;\n return manifestToIntentCatalogEntry({ catalogId: applet.catalogId, title: applet.title, archetypes: archetypes.map((contract) => ({ ...contract, params: [...contract.params] })) });\n}\n\n/**\n * The applets the user has run, persisted at `kernl:installed:v1`.\n *\n * Installing happens when the shell plans a verified applet, so the routing\n * contracts always come from a verified manifest (NAP-INTENT, \"Runtime\n * Behavior\"). Advertisements are routing hints; they grant nothing.\n *\n * @param storage - Where the list is kept.\n * @param now - Clock for `installedAt`.\n * @returns The installed set.\n * @example\n * ```ts\n * const installed = createInstalledApplets(localStorage);\n * installed.install(summary);\n * installed.catalog(); // [{ id: 'nip5d:35129:…:notepad', archetypes: { 'text-editor': … } }]\n * ```\n */\nexport function createInstalledApplets(storage: StorageLike, now: () => number = Date.now): InstalledApplets {\n const store = createNamespacedStore(storage, 'kernl');\n const stored = store.getJson<unknown>(STORAGE_KEY, []);\n const changes$ = new BehaviorSubject<readonly InstalledApplet[]>(Object.freeze(Array.isArray(stored) ? stored.filter(isInstalled) : []));\n\n const commit = (next: readonly InstalledApplet[]): void => {\n store.setJson(STORAGE_KEY, next);\n changes$.next(Object.freeze([...next]));\n };\n\n return {\n list: () => changes$.value,\n get: (catalogId) => changes$.value.find((applet) => applet.catalogId === catalogId),\n install(summary) {\n const { manifest } = summary;\n const previous = changes$.value.find((applet) => applet.catalogId === manifest.catalogId);\n const applet: InstalledApplet = Object.freeze({\n catalogId: manifest.catalogId,\n address: summary.address,\n title: summary.title,\n publisher: summary.publisher,\n contracts: Object.freeze(manifest.archetypes.map((entry) => Object.freeze({ slug: entry.slug, convention: entry.convention, params: Object.freeze([...entry.params]) }))),\n installedAt: previous?.installedAt ?? now(),\n });\n commit(previous ? changes$.value.map((entry) => (entry === previous ? applet : entry)) : [...changes$.value, applet]);\n return applet;\n },\n remove(catalogId) {\n if (changes$.value.some((applet) => applet.catalogId === catalogId)) commit(changes$.value.filter((applet) => applet.catalogId !== catalogId));\n },\n catalog: () => changes$.value.map(toCatalogEntry).filter((entry): entry is IntentCatalogEntry => entry !== undefined),\n changes$: changes$.asObservable(),\n };\n}\n","import { createCatalogIntentResolver, type IntentCandidate, type IntentDispatchParams, type IntentRequest, type IntentResolver, type IntentResult } from '@kehto/services';\nimport type { HandlerChoice, HandlerOption, HandlerPrompt } from '../types.js';\nimport type { HandlerDefaults } from './defaults.js';\nimport type { InstalledApplet, InstalledApplets } from './installed.js';\nimport { catalogIdForRef, preferredHandlers } from './preferences.js';\n\n/** What {@link createIntentRouter} needs. */\nexport interface IntentRouterOptions {\n readonly installed: InstalledApplets;\n readonly defaults: HandlerDefaults;\n /** Ask the user to pick a handler; absent in hosts with no chooser. */\n readonly choose?: (prompt: HandlerPrompt) => Promise<HandlerChoice | undefined>;\n /** A plain name for the applet that asked, from its runtime-attested catalogue id. */\n readonly describeSender: (sender: string) => string;\n /** Start or reuse the target and deliver; the promise settles when delivery succeeded or failed for good. */\n readonly deliver: (params: IntentDispatchParams) => Promise<void>;\n}\n\n/** kehto's resolver plus the shell's change notifications. */\nexport interface IntentRouter extends IntentResolver {\n notifyChanged(archetype: string): void;\n}\n\n/** Failures the shell answers by offering to find a handler in the store. */\nconst NO_HANDLER: ReadonlySet<string> = new Set(['no handler', 'unsupported convention', 'unsupported action']);\n\nconst isExplicit = (handler: string | undefined): boolean => handler !== undefined && handler !== 'default' && handler !== 'choose';\n\n/**\n * kernl's NAP-INTENT routing over kehto's `createCatalogIntentResolver`.\n *\n * kehto applies the spec's precedence and exact convention matching; kernl\n * supplies the installed catalogue, the user's defaults, the chooser and\n * delivery. The user's published preferences rank the chooser and pre-select a\n * handler when exactly one compatible preferred handler is installed. When no\n * installed applet can take the request, the user is asked once to pick one\n * from the store; a handler picked that way is used for this request only\n * through a one-time explicit authorisation, so an applet can never address a\n * handler the user did not choose (NAP-INTENT, \"Runtime Behavior\").\n *\n * @param options - Installed set, defaults, chooser, sender names and delivery.\n * @returns The resolver for kehto's intent service.\n * @example\n * ```ts\n * const router = createIntentRouter({ installed, defaults, choose, describeSender, deliver });\n * createIntentService({ resolver: router, resolveSender });\n * ```\n */\nexport function createIntentRouter(options: IntentRouterOptions): IntentRouter {\n const { installed, defaults } = options;\n const pending = new Map<string, IntentRequest>();\n const rerouted = new Map<string, string>();\n const authorised = new Set<string>();\n const pairKey = (sender: string, handler: string): string => `${sender}\\n${handler}`;\n\n async function ask(request: IntentRequest, candidates: readonly IntentCandidate[], sender: string): Promise<HandlerChoice | undefined> {\n if (!options.choose) return undefined;\n const preferred = preferredHandlers(defaults.synced(request.archetype), request.convention);\n const rank = (id: string): number => (preferred.includes(id) ? preferred.indexOf(id) : preferred.length);\n const choices: HandlerOption[] = candidates\n .map((candidate) => {\n // Candidates come from the installed catalogue, so each one is installed.\n const applet = installed.get(candidate.id) as InstalledApplet;\n return { id: candidate.id, title: applet.title, address: applet.address, preferred: preferred.includes(candidate.id) };\n })\n .sort((a, b) => rank(a.id) - rank(b.id));\n const hint = request.handlerHint?.address;\n const choice = await options.choose({\n archetype: request.archetype,\n action: request.action,\n convention: request.convention,\n source: options.describeSender(sender),\n options: choices,\n ...(hint ? { recommended: hint } : {}),\n });\n if (choice?.remember) await defaults.set(request.archetype, choice.id).catch(() => undefined);\n return choice;\n }\n\n async function chooseHandler(archetype: string, candidates: readonly IntentCandidate[], sender: string): Promise<string | undefined> {\n // kehto calls this only from inside `invoke`, which recorded the request for this sender.\n const request = pending.get(sender) as IntentRequest;\n const preferred = preferredHandlers(defaults.synced(archetype), request.convention).filter((id) => candidates.some((candidate) => candidate.id === id));\n if (preferred.length === 1 && request.handler !== 'choose') return preferred[0];\n const choice = await ask(request, candidates, sender);\n if (choice && !candidates.some((candidate) => candidate.id === choice.id)) {\n rerouted.set(sender, choice.id);\n return undefined;\n }\n return choice?.id;\n }\n\n const resolver = createCatalogIntentResolver({\n loadCatalog: () => installed.catalog(),\n targets: { accept: (params) => ({ completion: options.deliver(params) }) },\n getDefaultHandler: (archetype) => {\n const id = defaults.get(archetype);\n return id && installed.get(id) ? id : undefined;\n },\n // Without a chooser kehto refuses an undecided request as \"invoke rejected\"; with one, a dismissal is \"user cancelled\".\n ...(options.choose ? { chooseHandler } : {}),\n authorizeExplicitHandler: (sender, handler) => authorised.delete(pairKey(sender, handler)),\n resolveHandlerHint: (hint, candidates) => candidates.find((candidate) => candidate.id === catalogIdForRef(hint.address))?.id,\n });\n\n async function rerouteFor(request: IntentRequest, result: Extract<IntentResult, { ok: false }>, sender: string): Promise<string | undefined> {\n const picked = rerouted.get(sender);\n rerouted.delete(sender);\n if (picked) return picked;\n if (!NO_HANDLER.has(result.error) || isExplicit(request.handler)) return undefined;\n return (await ask(request, [], sender))?.id;\n }\n\n return {\n async invoke(request, context) {\n pending.set(context.sender, request);\n let handler: string | undefined;\n try {\n const result = await resolver.invoke(request, context);\n if (result.ok) return result;\n handler = await rerouteFor(request, result, context.sender);\n if (!handler || !installed.get(handler)) return result;\n authorised.add(pairKey(context.sender, handler));\n return await resolver.invoke({ ...request, handler }, context);\n } finally {\n pending.delete(context.sender);\n if (handler) authorised.delete(pairKey(context.sender, handler));\n }\n },\n available: (archetype) => resolver.available(archetype),\n handlers: () => resolver.handlers(),\n // kehto's catalogue resolver always implements it; the interface marks it optional for other resolvers.\n onChanged: resolver.onChanged as NonNullable<IntentResolver['onChanged']>,\n notifyChanged: (archetype) => resolver.notifyChanged(archetype),\n };\n}\n","import { auditTime, catchError, EMPTY, from, lastValueFrom, map, merge, mergeAll, type Observable, scan, share, takeUntil, tap, timer } from 'rxjs';\nimport { getSeenRelays, type Filter } from 'applesauce-core/helpers';\nimport { NAPPLET_KIND_NAMED, NAPPLET_KIND_ROOT } from '@kehto/nip/5d';\nimport type { NostrEvent, NostrFilter } from '@napplet/core';\nimport type { RelayTiers } from '../types.js';\nimport { asFilters, type ApplesaucePool } from '../applesauce/relay-hooks.js';\nimport { newestEntries, toCatalogEntry, type CatalogEntry } from './entry.js';\nimport { DELETION_KIND, isWithdrawn, withdraw, type Withdrawals } from './withdrawn.js';\n\n/**\n * How many manifests the store asks each relay for.\n *\n * @example\n * ```ts\n * await loadCatalog(pool, tiers, { limit: CATALOG_LIMIT });\n * ```\n */\nexport const CATALOG_LIMIT = 500;\n\n/**\n * The longest the store keeps asking a relay that has not finished. Entries are\n * listed as they arrive, so this is the outer bound, not a wait (D-028).\n *\n * @example\n * ```ts\n * await loadCatalog(pool, tiers, { timeoutMs: CATALOG_TIMEOUT_MS }); // at most 30 s\n * ```\n */\nexport const CATALOG_TIMEOUT_MS = 30_000;\n\n/**\n * When nothing has arrived after this long, the stream says so with an empty\n * list and keeps listening; it is a moment to tell the person, not a cut-off.\n *\n * @example\n * ```ts\n * streamCatalog(pool, tiers, { settleMs: CATALOG_SETTLE_MS });\n * ```\n */\nexport const CATALOG_SETTLE_MS = 3000;\n\n/**\n * How often, at most, the streamed catalogue emits while manifests pour in.\n *\n * @example\n * ```ts\n * streamCatalog(pool, tiers); // emits at most every CATALOG_EMIT_MS\n * ```\n */\nexport const CATALOG_EMIT_MS = 120;\n\n/** Options for {@link loadCatalog}. */\nexport interface LoadCatalogOptions {\n /** Per-relay manifest limit; {@link CATALOG_LIMIT} by default. */\n readonly limit?: number;\n /** Only manifests from these publishers. */\n readonly publishers?: readonly string[];\n /** The outer bound on a relay that never finishes; {@link CATALOG_TIMEOUT_MS} by default. */\n readonly timeoutMs?: number;\n /** How often the stream emits at most; {@link CATALOG_EMIT_MS} by default. */\n readonly emitMs?: number;\n /** When an empty list is emitted if nothing has arrived; {@link CATALOG_SETTLE_MS} by default. */\n readonly settleMs?: number;\n /** Manifests seen before, listed at once while the relays are asked for newer ones. */\n readonly cache?: (filters: Filter[]) => Promise<NostrEvent[]>;\n /** Where manifests from the relays are kept, so the event cache holds them for the next visit. */\n readonly store?: { add(event: NostrEvent): unknown };\n}\n\n/**\n * The relays the store reads: the applet catalogue tier first, then the\n * public relays most publishers also write to.\n *\n * @param tiers - The shell's relay tiers.\n * @returns Deduplicated relay URLs.\n * @example\n * ```ts\n * catalogRelays(tiers); // ['wss://relay.napplet.soy', 'wss://relay.damus.io', …]\n * ```\n */\nexport function catalogRelays(tiers: RelayTiers): readonly string[] {\n const { apps, super: shared } = tiers.get();\n return Object.freeze([...new Set([...apps, ...shared])]);\n}\n\nfunction catalogFilters(options: LoadCatalogOptions): NostrFilter[] {\n const limit = options.limit ?? CATALOG_LIMIT;\n const authors = options.publishers ? { authors: [...options.publishers] } : {};\n return [\n { kinds: [NAPPLET_KIND_NAMED, NAPPLET_KIND_ROOT], limit, ...authors },\n { kinds: [DELETION_KIND], '#k': [String(NAPPLET_KIND_NAMED), String(NAPPLET_KIND_ROOT)], limit, ...authors },\n ];\n}\n\ninterface Found {\n readonly listed: readonly { readonly event: NostrEvent; readonly entry: CatalogEntry }[];\n readonly withdrawn: Withdrawals;\n}\n\nfunction hintsFor(event: NostrEvent, relays: readonly string[]): readonly string[] {\n const seen = [...(getSeenRelays(event) ?? [])];\n return seen.length > 0 ? seen.slice(0, 2) : relays.slice(0, 2);\n}\n\n/**\n * Stream the applets published to the store's relays.\n *\n * Root and named manifests are fetched; pinned versions are reached by\n * pasting their address. A manifest its publisher deleted (NIP-09) is not\n * listed, even when a relay still serves it. The list is emitted again as manifests arrive, so\n * the first relay to answer fills the store while slower ones are still\n * talking. A relay that fails contributes nothing and never discards what\n * others sent; when nothing has arrived after `settleMs` an empty list says\n * so, and listening goes on. The stream completes when every relay has\n * finished, or at the outer bound.\n *\n * @param pool - The shared applesauce pool.\n * @param tiers - The shell's relay tiers.\n * @param options - Limit, publisher filter and outer bound.\n * @returns The growing list, one entry per applet, newest first.\n * @example\n * ```ts\n * streamCatalog(pool, tiers).subscribe((entries) => render(searchCatalog(entries, { text: 'notes' })));\n * ```\n */\nexport function streamCatalog(pool: ApplesaucePool, tiers: RelayTiers, options: LoadCatalogOptions = {}): Observable<readonly CatalogEntry[]> {\n const relays = catalogRelays(tiers);\n const filters = asFilters(catalogFilters(options));\n const cached = options.cache ? from(options.cache(filters).catch(() => [])).pipe(mergeAll()) : EMPTY;\n const live = pool.request([...relays], filters).pipe(\n takeUntil(timer(options.timeoutMs ?? CATALOG_TIMEOUT_MS)),\n catchError(() => EMPTY),\n tap((event) => options.store?.add(event)),\n );\n const events = merge(cached, live);\n const found = events.pipe(\n scan((state: Found, event): Found => {\n if (event.kind === DELETION_KIND) return { ...state, withdrawn: withdraw(state.withdrawn, event) };\n const entry = toCatalogEntry(event, hintsFor(event, relays));\n return entry ? { ...state, listed: [...state.listed, { event, entry }] } : state;\n }, { listed: [], withdrawn: new Map() }),\n );\n const listed = (state: Found): readonly CatalogEntry[] => newestEntries(state.listed.filter(({ event }) => !isWithdrawn(event, state.withdrawn)).map(({ entry }) => entry));\n const lists = found.pipe(auditTime(options.emitMs ?? CATALOG_EMIT_MS), map(listed), share());\n const nothingYet = timer(options.settleMs ?? CATALOG_SETTLE_MS).pipe(map((): readonly CatalogEntry[] => Object.freeze([])), takeUntil(lists));\n return merge(nothingYet, lists);\n}\n\n/**\n * List the applets published to the store's relays, once every relay has\n * finished or the outer bound passed. Prefer {@link streamCatalog} for UI.\n *\n * @param pool - The shared applesauce pool.\n * @param tiers - The shell's relay tiers.\n * @param options - Limit and publisher filter.\n * @returns One entry per applet, newest first.\n * @example\n * ```ts\n * const entries = await loadCatalog(pool, tiers);\n * searchCatalog(entries, { text: 'notes' });\n * ```\n */\nexport async function loadCatalog(pool: ApplesaucePool, tiers: RelayTiers, options: LoadCatalogOptions = {}): Promise<readonly CatalogEntry[]> {\n return lastValueFrom(streamCatalog(pool, tiers, options), { defaultValue: Object.freeze([]) });\n}\n","import type { NostrEvent } from '@napplet/core';\n\n/** Deletion requests (NIP-09). */\nexport const DELETION_KIND = 5;\n\n/** What a publisher withdrew: `pubkey|reference` to the newest deletion's time. */\nexport type Withdrawals = ReadonlyMap<string, number>;\n\nconst referenceKey = (pubkey: string, reference: string): string => `${pubkey}|${reference}`;\n\n/**\n * Record what a deletion request withdraws. Only the author's own events and\n * addresses count: a deletion signed by someone else withdraws nothing.\n *\n * @param withdrawals - What was withdrawn so far.\n * @param deletion - A kind 5 event.\n * @returns The withdrawals including this request.\n * @example\n * ```ts\n * let withdrawn: Withdrawals = new Map();\n * withdrawn = withdraw(withdrawn, deletionEvent);\n * ```\n */\nexport function withdraw(withdrawals: Withdrawals, deletion: NostrEvent): Withdrawals {\n const next = new Map(withdrawals);\n for (const [name, value] of deletion.tags) {\n if ((name !== 'e' && name !== 'a') || typeof value !== 'string') continue;\n if (name === 'a' && value.split(':')[1] !== deletion.pubkey) continue;\n const key = referenceKey(deletion.pubkey, value);\n next.set(key, Math.max(next.get(key) ?? 0, deletion.created_at));\n }\n return next;\n}\n\n/**\n * Whether the publisher withdrew this manifest: its id was deleted, or its\n * address was deleted at or after the time it was published.\n *\n * @param event - A manifest event.\n * @param withdrawals - What publishers withdrew.\n * @returns True when the manifest should not be listed.\n * @example\n * ```ts\n * isWithdrawn(manifest, withdraw(new Map(), deletionOfIt)); // true\n * ```\n */\nexport function isWithdrawn(event: NostrEvent, withdrawals: Withdrawals): boolean {\n if (withdrawals.has(referenceKey(event.pubkey, event.id))) return true;\n const identifier = event.tags.find((tag) => tag[0] === 'd')?.[1] ?? '';\n const at = withdrawals.get(referenceKey(event.pubkey, `${event.kind}:${event.pubkey}:${identifier}`));\n return at !== undefined && at >= event.created_at;\n}\n","import type { CatalogEntry } from './entry.js';\n\n/** What the store filters by. Every part is optional; an empty query lists everything. */\nexport interface CatalogQuery {\n /** Free text, matched loosely against title, topics, roles, description and publisher. */\n readonly text?: string;\n /** Topics the entry must carry, all of them. */\n readonly topics?: readonly string[];\n /** When given, entries that require a domain outside this list are left out. */\n readonly available?: readonly string[];\n /** When given, only entries that accept this convention identity, such as `napplet:profile/open`. */\n readonly convention?: string;\n}\n\n/** A topic and how many listed applets carry it. */\nexport interface TopicCount {\n readonly topic: string;\n readonly count: number;\n}\n\nconst FIELD_WEIGHTS = { title: 8, topics: 5, archetypes: 5, description: 2, publisher: 1 } as const;\n\n/**\n * How well one search word matches a field: a whole-word hit beats a prefix,\n * a prefix beats a substring, and a substring beats the word's letters\n * appearing in order within one word of the field, which forgives a typo\n * without letting a long description match anything. Zero when none hold.\n *\n * @param word - One lower-case search word.\n * @param field - Lower-case field text.\n * @returns A score from 0 to 4.\n * @example\n * ```ts\n * fuzzyScore('chess', 'chess club'); // 4\n * fuzzyScore('chss', 'chess club'); // 1\n * ```\n */\nexport function fuzzyScore(word: string, field: string): number {\n if (word === '' || field === '') return 0;\n const words = field.split(/[^\\p{L}\\p{N}]+/u);\n if (words.includes(word)) return 4;\n if (words.some((part) => part.startsWith(word))) return 3;\n if (field.includes(word)) return 2;\n return word.length > 2 && words.some((part) => inOrder(word, part)) ? 1 : 0;\n}\n\n/** Whether every letter of `word` appears in `part`, in order: \"mnswpr\" in \"minesweeper\". */\nfunction inOrder(word: string, part: string): boolean {\n let at = 0;\n for (const char of part) if (char === word[at]) at += 1;\n return at === word.length;\n}\n\nfunction wordScore(word: string, entry: CatalogEntry): number {\n const fields: Record<keyof typeof FIELD_WEIGHTS, string> = {\n title: entry.title.toLowerCase(),\n topics: entry.topics.join(' '),\n archetypes: entry.archetypes.join(' '),\n description: entry.description.toLowerCase(),\n publisher: entry.publisher,\n };\n let best = 0;\n for (const [field, weight] of Object.entries(FIELD_WEIGHTS)) {\n best = Math.max(best, fuzzyScore(word, fields[field as keyof typeof FIELD_WEIGHTS]) * weight);\n }\n return best;\n}\n\nfunction textScore(text: string, entry: CatalogEntry): number {\n const words = text.toLowerCase().split(/\\s+/).filter(Boolean);\n let total = 0;\n for (const word of words) {\n const score = wordScore(word, entry);\n if (score === 0) return 0;\n total += score;\n }\n return words.length === 0 ? 1 : total;\n}\n\nfunction passesFilters(entry: CatalogEntry, query: CatalogQuery): boolean {\n if (query.topics?.some((topic) => !entry.topics.includes(topic))) return false;\n if (query.available && entry.requires.some((domain) => !query.available?.includes(domain))) return false;\n return query.convention === undefined || entry.conventions.includes(query.convention);\n}\n\n/**\n * Filter and rank store entries.\n *\n * Every search word has to match some field; entries are ordered by score,\n * then by how recently they were published.\n *\n * @param entries - The listed applets.\n * @param query - Text, topics, the domains the shell offers and an optional convention.\n * @returns Matching entries, best first.\n * @example\n * ```ts\n * searchCatalog(entries, { text: 'mine swep', topics: ['game'], available: kernl.grants.availableDomains() });\n * ```\n */\nexport function searchCatalog(entries: readonly CatalogEntry[], query: CatalogQuery = {}): readonly CatalogEntry[] {\n const scored: Array<{ entry: CatalogEntry; score: number }> = [];\n for (const entry of entries) {\n if (!passesFilters(entry, query)) continue;\n const score = textScore(query.text ?? '', entry);\n if (score > 0) scored.push({ entry, score });\n }\n scored.sort((a, b) => b.score - a.score || b.entry.publishedAt - a.entry.publishedAt);\n return Object.freeze(scored.map(({ entry }) => entry));\n}\n\n/**\n * The topics most listed applets carry, for the store's filter bubbles.\n *\n * @param entries - The listed applets.\n * @param limit - How many topics to return.\n * @returns Topics by count, then alphabetically.\n * @example\n * ```ts\n * popularTopics(entries, 3); // [{ topic: 'game', count: 14 }, { topic: '3d', count: 5 }, …]\n * ```\n */\nexport function popularTopics(entries: readonly CatalogEntry[], limit = 12): readonly TopicCount[] {\n const counts = new Map<string, number>();\n for (const entry of entries) for (const topic of entry.topics) counts.set(topic, (counts.get(topic) ?? 0) + 1);\n return Object.freeze(\n [...counts]\n .map(([topic, count]) => ({ topic, count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OAAO,OAAO,OAAO,IAAI,CAAC,EAAE,MAAM,MAAM,KAAK,CAAC;AACvD;AAaO,SAAS,cAAc,SAAkC,QAAQ,IAA2B;AACjG,QAAM,SAAS,oBAAI,IAAoB;AACvC,aAAW,SAAS,QAAS,YAAW,SAAS,MAAM,OAAQ,QAAO,IAAI,QAAQ,OAAO,IAAI,KAAK,KAAK,KAAK,CAAC;AAC7G,SAAO,OAAO;AAAA,IACZ,CAAC,GAAG,MAAM,EACP,IAAI,CAAC,CAAC,OAAO,KAAK,OAAO,EAAE,OAAO,MAAM,EAAE,EAC1C,KAAK,CAAC,GAAG,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,cAAc,EAAE,KAAK,CAAC,EAClE,MAAM,GAAG,KAAK;AAAA,EACnB;AACF;;;AtDlHO,IAAM,eAAe;AAWrB,IAAM,0BAAkC,6BAA6B;","names":["BehaviorSubject","newest","text","BehaviorSubject","relays","filter","BehaviorSubject","map","normalizeRelayUrl","relays","from","relayUrls","kinds","filter","map","relays","from","BehaviorSubject","relays","relayUrls","lastValueFrom","map","relays","text","text","coordinate","lastValueFrom","map","merge","switchMap","timer","toArray","unique","relays","newest","filter","switchMap","timer","merge","map","relays","lastValueFrom","toArray","newest","text","BehaviorSubject","BehaviorSubject","take","resolveWindow","Subject","STORAGE_KEY","Subject","getInboxes","getOutboxes","kinds","lastValueFrom","timer","toArray","isReplaceable","lastValueFrom","timer","toArray","isReplaceable","resolveApplet","STORAGE_KEY","kinds","getConversationParticipants","unixNow","summarize","lastValueFrom","relays","relays","unixNow","signerOf","kinds","getConversationParticipants","relays","kinds","mergeRelaySets","verifyEvent","getConversationParticipants","verifyEvent","getConversationParticipants","kinds","mergeRelaySets","verifyEvent","text","CAPABILITIES","relays","filter","verifyEvent","signerOf","from","unixNow","lastValueFrom","toArray","relays","lastValueFrom","toArray","bytesToHex","kinds","mergeRelaySets","text","bytesToHex","mergeRelaySets","filter","relays","kinds","latest","group","CAPABILITIES","unixNow","signerOf","page","BehaviorSubject","catchError","EMPTY","map","of","switchMap","unixNow","stateFor","of","catchError","EMPTY","switchMap","map","BehaviorSubject","unixNow","relays","from","map","takeUntil","catchError","distinctUntilChanged","EMPTY","endWith","filter","firstValueFrom","ignoreElements","map","merge","Observable","switchMap","take","timer","getOutboxes","getProfileContent","HEX_KEY","getProfileContent","relays","map","getOutboxes","filter","take","switchMap","Observable","distinctUntilChanged","timer","card","catchError","EMPTY","ignoreElements","endWith","firstValueFrom","merge","map","takeUntil","verifyEvent","text","relays","verifyEvent","verifyEvent","TIERS","verifyEvent","keyOf","relays","BehaviorSubject","map","of","Subject","Subscription","switchMap","createGuardConfig","originRegistry","lastValueFrom","Subject","takeUntil","timer","toArray","verifyEvent","HEX_64","tag","newest","verifyEvent","Subject","lastValueFrom","takeUntil","timer","toArray","BehaviorSubject","STORAGE_KEY","toCatalogEntry","BehaviorSubject","applet","rank","originRegistry","auditTime","catchError","EMPTY","lastValueFrom","map","merge","share","takeUntil","timer","deletion","relays","EMPTY","takeUntil","timer","catchError","merge","auditTime","map","share","lastValueFrom","Subscription","switchMap","map","of","Subject","BehaviorSubject","createGuardConfig","text"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/persistence/store.ts","../src/relays/tiers.ts","../src/relays/publish-outcome.ts","../src/relays/directory.ts","../src/relays/mailboxes.ts","../src/applesauce/relay-hooks.ts","../src/applesauce/relay-backend.ts","../src/applesauce/auth-hooks.ts","../src/applesauce/identity-providers.ts","../src/applesauce/accounts.ts","../src/applets/pointer.ts","../src/applets/builtin.ts","../src/applets/resolve.ts","../src/catalog/entry.ts","../src/applets/plan.ts","../src/applets/mount.ts","../src/guard/pipeline.ts","../src/guard/runtime-rules.ts","../src/grants/domain-capabilities.ts","../src/grants/grants.ts","../src/consent/describe-change.ts","../src/consent/handler.ts","../src/messaging/default-registry.ts","../src/messaging/availability.ts","../src/messaging/private-backend.ts","../src/messaging/signer-backend.ts","../src/messaging/conversation-store.ts","../src/messaging/inbox-relays.ts","../src/messaging/legacy-backend.ts","../src/messaging/ratchet-backend.ts","../src/messaging/ratchet-storage.ts","../src/messaging/group-backend.ts","../src/messaging/group-network.ts","../src/messaging/group-session.ts","../src/messaging/group-storage.ts","../src/bridges/default-registry.ts","../src/messaging/label-conversations.ts","../src/files/file-servers.ts","../src/files/uploader.ts","../src/applets/applet-config.ts","../src/social/common-actions.ts","../src/kernl-network.ts","../src/profiles/profiles.ts","../src/multiplayer/remote-tools.ts","../src/multiplayer/window-identities.ts","../src/multiplayer/settings.ts","../src/multiplayer/tool-discovery.ts","../src/multiplayer/direct-connections.ts","../src/multiplayer/direct-signaling.ts","../src/kernl-services.ts","../src/kernl-adapter.ts","../src/kernl-lifecycle.ts","../src/kernl.ts","../src/kernl-intents.ts","../src/intents/defaults.ts","../src/intents/preferences.ts","../src/intents/delivery.ts","../src/intents/installed.ts","../src/intents/router.ts","../src/catalog/fetch.ts","../src/catalog/withdrawn.ts","../src/catalog/search.ts"],"sourcesContent":["/**\n * Opinionated shell composition over kehto and applesauce: adapters, applet\n * resolution and mounting, grants, consent summaries, layouts and persistence.\n *\n * @packageDocumentation\n */\nimport { renderNappletFramePolicyMeta } from '@kehto/shell';\n\n/**\n * The npm package name, shared by both registry builds.\n *\n * @example\n * ```ts\n * PACKAGE_NAME; // '@kernlize/core'\n * ```\n */\nexport const PACKAGE_NAME = '@kernlize/core';\n\n/**\n * The `<meta>` element the host page puts in its `<head>` so applet frames can\n * never navigate away from their verified `srcdoc`. Rendered once by kehto.\n *\n * @example\n * ```ts\n * document.head.insertAdjacentHTML('afterbegin', KERNL_FRAME_POLICY_META);\n * ```\n */\nexport const KERNL_FRAME_POLICY_META: string = renderNappletFramePolicyMeta();\n\nexport type * from './types.js';\n\nexport { createNamespacedStore, type NamespacedStore } from './persistence/store.js';\nexport { DEFAULT_RELAY_TIERS, createRelayTiers } from './relays/tiers.js';\nexport type { TierMap } from './relays/tiers.js';\nexport { describeOutcome, relayUrls, summarizePublish, toRelayUrl, type PublishAnswer, type PublishOutcome } from './relays/publish-outcome.js';\nexport {\n DEFAULT_MONITOR_RELAYS,\n DEFAULT_SUGGESTIONS,\n createRelayDirectory,\n type DirectoryPool,\n type RelayDirectory,\n type RelayDirectoryOptions,\n type RelayListing,\n type SuggestOptions,\n type SuggestPurpose,\n} from './relays/directory.js';\nexport {\n createAccountMailboxes,\n mailboxTags,\n mailboxesFromEvent,\n type AccountMailboxes,\n type AccountMailboxesOptions,\n type MailboxPool,\n type MailboxSigner,\n type MailboxState,\n type Mailboxes,\n} from './relays/mailboxes.js';\n\nexport {\n SHELL_RELAY_OPTIONS,\n createRelayPoolHooks,\n createRelayPoolLike,\n selectRelayTier,\n subscribeWithEose,\n type ApplesaucePool,\n type EoseSubscription,\n} from './applesauce/relay-hooks.js';\nexport { createAppletRelayBackend, createAppletRelayService, createDmRelayPool, createOutboxRelayPool, publishAccepted, type OutboxRelayPoolLike } from './applesauce/relay-backend.js';\nexport { createAuthHooks, isReadOnlyAccount, wrapAccountSigner } from './applesauce/auth-hooks.js';\nexport {\n createIdentityProviders,\n createReplaceableLoader,\n lookupRelaysOf,\n type IdentityProfile,\n type IdentityProviderOptions,\n type IdentityProviders,\n type RelayPermissions,\n} from './applesauce/identity-providers.js';\nexport { KernlAccountManager, PLAINTEXT_KEY_ACCOUNT_TYPES, createKernlAccounts } from './applesauce/accounts.js';\n\nexport { decodePointer } from './applets/pointer.js';\nexport { BUILTIN_PUBLISHER, builtinAddress, resolveBuiltin } from './applets/builtin.js';\nexport {\n BLOB_TIMEOUT_MS,\n MANIFEST_TIMING,\n defaultFetchBlob,\n fetchManifestEvent,\n openDefaultArtifactCache,\n resolveApplet,\n summarize,\n type ManifestTiming,\n type PublishedPointer,\n type ResolveAppletOptions,\n type ResolvedApplet,\n} from './applets/resolve.js';\nexport { planMount, type PlanMountOptions } from './applets/plan.js';\nexport { CONTROLLER_DENY_POLICY, mountApplet, type MountDeps, type MountGuardHooks, type MountedApplet } from './applets/mount.js';\n\nexport {\n createGuardPipeline,\n type GuardPipeline,\n type GuardPipelineOptions,\n type PipelineDisposition,\n type WindowResolution,\n} from './guard/pipeline.js';\nexport {\n RUNTIME_FIREWALL_STORAGE_KEY,\n RUNTIME_OP_CLASSES,\n applyRuntimeFirewallProfile,\n applyRuntimeFirewallRules,\n createRuntimeFirewallHooks,\n runtimeFirewallRules,\n toGuardEvent,\n type RuntimeFirewallHooks,\n type RuntimeFirewallHooksOptions,\n type RuntimeFirewallRules,\n type RuntimeFirewallState,\n type RuntimeRateRule,\n} from './guard/runtime-rules.js';\n\nexport { BASELINE_DOMAINS, DOMAIN_CAPABILITIES, capabilitiesForDomain, capabilitiesForDomains } from './grants/domain-capabilities.js';\nexport { createEnvironmentResolver, createGrants, type GrantsOptions, type KernlGrants } from './grants/grants.js';\n\nexport { abbreviate, describeChange, isDestructiveKind } from './consent/describe-change.js';\nexport {\n CURRENT_VERSION_TIMEOUT_MS,\n UNKNOWN_CURRENT_VERSION,\n createConsentHandler,\n createSigningConsent,\n lookupReplaceable,\n type LookupBefore,\n type LookupReplaceableOptions,\n type ResolveAppletIdentity,\n type SigningConsent,\n type SigningConsentOptions,\n type SigningTemplate,\n} from './consent/handler.js';\n\nexport {\n createColumnsLayout,\n createDefaultLayouts,\n createDwindleLayout,\n createLayoutRegistry,\n createMasterStackLayout,\n createWindowManager,\n floatingLayout,\n type LayoutChoice,\n type LayoutEntry,\n type LayoutOptions,\n type LayoutRegistry,\n type LayoutStrategy,\n type ManagedWindow,\n type MasterStackOptions,\n type Rect,\n type VisibilityTarget,\n type WindowManager,\n type WindowManagerOptions,\n type WindowManagerState,\n type WindowPlacement,\n type WindowSize,\n type WindowState,\n} from './wm/index.js';\nexport { createFallbackSubtle, installCryptoFallback, randomUuidFallback, renderRandomUuidFallbackScript, type CryptoFallbackReport, type CryptoScope } from './crypto/index.js';\nexport {\n attachEventCache,\n createEventCache,\n createIndexedDbCacheAdapter,\n createMemoryCacheAdapter,\n createSqliteOpfsCacheAdapter,\n defaultWebCacheAdapters,\n fromEventDatabase,\n isCorruptionError,\n openEventCache,\n type AttachedEventCache,\n type AttachEventCacheOptions,\n type CacheRecoveryEvent,\n type EventCache,\n type EventCacheAdapter,\n type EventRecords,\n type FilenameStorage,\n type IndexedDbCacheOptions,\n type LockManagerLike,\n type OpenEventCacheOptions,\n type SqliteDriver,\n type SqliteFiles,\n type SqliteOpfsOptions,\n type SqlStatement,\n type SqlValue,\n connectEventCache,\n type ConnectedEventCache,\n type EventCacheOpener,\n} from './cache/index.js';\n\nexport { createDefaultMessaging, type DefaultMessagingOptions } from './messaging/default-registry.js';\nexport { MESSAGING_UNAVAILABLE_REASONS, messagingSigner, signerAvailability, type MessagingEncryption } from './messaging/availability.js';\nexport type { SignerMessagingOptions } from './messaging/signer-backend.js';\nexport { createPrivateMessagesBackend } from './messaging/private-backend.js';\nexport { createLegacyMessagesBackend } from './messaging/legacy-backend.js';\nexport { createRatchetMessagesBackend, type RatchetMessagingOptions } from './messaging/ratchet-backend.js';\nexport { createGroupMessagesBackend, type GroupMessagingOptions } from './messaging/group-backend.js';\nexport { createSealedGroupStore, type SealedGroupStoreOptions } from './messaging/group-storage.js';\nexport { createGroupNetwork } from './messaging/group-network.js';\nexport type { InboxRelays } from './messaging/inbox-relays.js';\nexport { createSealedRatchetStorage, type SealedRatchetStorageOptions } from './messaging/ratchet-storage.js';\nexport { createDefaultBridges, type DefaultBridgesOptions } from './bridges/default-registry.js';\n\nexport { labelConversations } from './messaging/label-conversations.js';\nexport { createAccountFileServers, DEFAULT_FILE_SERVERS, fileServersFromEvent, fileServerTags, type AccountFileServers, type AccountFileServersOptions, type FileServerState } from './files/file-servers.js';\nexport { askUploadConsent, createBlossomUploader, describeUpload, sizeWords, type BlossomUploaderOptions, type MultiServerUpload, type UploadDetails } from './files/uploader.js';\nexport { createAppletConfig, type AppletConfigOptions, type SettingsPrompt } from './applets/applet-config.js';\nexport { createCommonActions, type CommonActionsOptions } from './social/common-actions.js';\nexport { commonActionsFor, createKernlNetwork, type KernlNetwork, type KernlNetworkParts } from './kernl-network.js';\nexport { createCvmRelayPool, createRemoteToolsService, mergeFamilies, type RemoteToolsOptions } from './multiplayer/remote-tools.js';\nexport { createWindowIdentities, type WindowIdentities } from './multiplayer/window-identities.js';\nexport { createMultiplayerSettings, validFamily, type MultiplayerSettings, type MultiplayerState } from './multiplayer/settings.js';\nexport { discoverToolFamilies, TOOL_DISCOVERY_TIMEOUT_MS, type ToolDiscoveryOptions, type ToolFamilyCandidate } from './multiplayer/tool-discovery.js';\nexport { createDirectConnectionsService, describeDirectConnection, directNamespace, type DirectConnectionsOptions } from './multiplayer/direct-connections.js';\nexport { createDirectSignaling, DIRECT_MAX_PAYLOAD_BYTES, DIRECT_SIGNAL_KIND, DIRECT_SIGNALING_PROFILE, type DirectSignalingOptions, type SignalRelay, type SignalSigner } from './multiplayer/direct-signaling.js';\nexport { LINK_PROTOCOLS, createKernlServices, isTheme, resourceInitFor, type DirectConnectionsDeps, type KernlServiceDeps, type KernlServices } from './kernl-services.js';\nexport { createShellAdapter, type ShellAdapterDeps } from './kernl-adapter.js';\nexport { createAppletLifecycle, grantNarrowingReason, resolveWindow, type AppletLifecycle, type LifecycleContext } from './kernl-lifecycle.js';\nexport { createKernl, toSession } from './kernl.js';\nexport { createProfiles, toProfileCard, type ProfileCard, type ProfileLoader, type ProfilePointer, type Profiles, type ProfilesOptions } from './profiles/profiles.js';\nexport { addressOf, newestEntries, toCatalogEntry, type CatalogEntry } from './catalog/entry.js';\nexport { CATALOG_EMIT_MS, CATALOG_LIMIT, CATALOG_SETTLE_MS, CATALOG_TIMEOUT_MS, catalogRelays, loadCatalog, streamCatalog, type LoadCatalogOptions } from './catalog/fetch.js';\nexport { fuzzyScore, popularTopics, searchCatalog, type CatalogQuery, type TopicCount } from './catalog/search.js';\nexport { createInstalledApplets, type InstallableApplet, type InstalledApplet, type InstalledApplets, type InstalledContract } from './intents/installed.js';\nexport {\n HANDLER_PREFERENCES_KIND,\n catalogIdForRef,\n parseHandlerPreferences,\n preferenceTemplate,\n preferredHandlers,\n refForCatalogId,\n type HandlerPreferences,\n} from './intents/preferences.js';\nexport { createHandlerDefaults, preferenceRelays, type HandlerDefaults, type HandlerDefaultsOptions, type PreferenceSigner } from './intents/defaults.js';\nexport { createIntentRouter, type IntentRouter, type IntentRouterOptions } from './intents/router.js';\nexport { DELIVERY_RETRY, createIntentDelivery, type IntentDeliveryOptions } from './intents/delivery.js';\nexport { createKernlIntents, type KernlIntentDeps, type KernlIntents } from './kernl-intents.js';\n","import type { StorageLike } from '../types.js';\n\n/** A prefixed JSON view over a {@link StorageLike}. */\nexport interface NamespacedStore {\n /** Read and parse a value; `fallback` when the key is absent or unreadable. */\n getJson<T>(key: string, fallback: T): T;\n /** Serialise and write a value. */\n setJson(key: string, value: unknown): void;\n remove(key: string): void;\n}\n\ntype ParsedJson = { readonly ok: true; readonly value: unknown } | { readonly ok: false };\n\nfunction parseJson(raw: string): ParsedJson {\n try {\n return { ok: true, value: JSON.parse(raw) };\n } catch {\n return { ok: false };\n }\n}\n\n/**\n * Create a store that keeps every kernl key under one prefix, so the host's\n * storage can also hold kehto's and the app's own keys without collisions.\n *\n * Corrupt JSON reads as the fallback rather than throwing: persisted state is\n * a convenience, and a damaged value must never stop the shell from booting.\n *\n * @param storage - Synchronous key-value storage; `localStorage` or a Map-backed fake.\n * @param prefix - Namespace prepended to every key, for example `kernl`.\n * @returns A namespaced JSON store.\n * @example\n * ```ts\n * const store = createNamespacedStore(localStorage, 'kernl');\n * store.setJson('relays:v1', { apps: ['wss://relay.napplet.soy'] });\n * store.getJson('relays:v1', {}); // { apps: [...] }\n * ```\n */\nexport function createNamespacedStore(storage: StorageLike, prefix: string): NamespacedStore {\n const keyFor = (key: string): string => `${prefix}:${key}`;\n return {\n getJson<T>(key: string, fallback: T): T {\n const raw = storage.getItem(keyFor(key));\n if (raw === null) return fallback;\n const parsed = parseJson(raw);\n return parsed.ok ? (parsed.value as T) : fallback;\n },\n setJson(key, value) {\n storage.setItem(keyFor(key), JSON.stringify(value));\n },\n remove(key) {\n storage.removeItem(keyFor(key));\n },\n };\n}\n","import { BehaviorSubject } from 'rxjs';\nimport type { RelayTier, RelayTiers, StorageLike } from '../types.js';\nimport { createNamespacedStore } from '../persistence/store.js';\n\n/** Relay URLs per tier, frozen. */\nexport type TierMap = Readonly<Record<RelayTier, readonly string[]>>;\n\n/**\n * Where the shell looks when the user has configured nothing.\n *\n * @example\n * ```ts\n * DEFAULT_RELAY_TIERS.apps; // ['wss://relay.napplet.soy', 'wss://relay.ditto.pub', 'wss://relay.nostr.com']\n * DEFAULT_RELAY_TIERS.outbox; // []\n * ```\n */\nexport const DEFAULT_RELAY_TIERS: TierMap = Object.freeze({\n discovery: ['wss://purplepag.es', 'wss://relay.nos.social'],\n // The catalogues the two public napplet stores read; together with `super` they hold every napplet either lists.\n apps: ['wss://relay.napplet.soy', 'wss://relay.ditto.pub', 'wss://relay.nostr.com'],\n outbox: [],\n super: ['wss://relay.damus.io', 'wss://nos.lol', 'wss://relay.primal.net'],\n});\n\nconst TIERS: readonly RelayTier[] = ['discovery', 'apps', 'outbox', 'super'];\nconst STORAGE_KEY = 'relays:v1';\n\nfunction freeze(tiers: Record<RelayTier, readonly string[]>): TierMap {\n return Object.freeze({\n discovery: Object.freeze([...tiers.discovery]),\n apps: Object.freeze([...tiers.apps]),\n outbox: Object.freeze([...tiers.outbox]),\n super: Object.freeze([...tiers.super]),\n });\n}\n\nfunction merge(base: TierMap, overrides: Partial<Record<RelayTier, readonly string[]>>): TierMap {\n const next = { ...base } as Record<RelayTier, readonly string[]>;\n for (const tier of TIERS) {\n const value = overrides[tier];\n if (Array.isArray(value)) next[tier] = value.filter((url) => typeof url === 'string');\n }\n return freeze(next);\n}\n\nfunction assertRelayUrl(url: string): void {\n if (!/^wss?:\\/\\/\\S+$/.test(url)) throw new Error('invalid:relay-url');\n}\n\n/**\n * Create the relay tier configuration the shell and kehto both read.\n *\n * kehto's `RelayConfigHooks` knows `discovery`, `super` and `outbox`; kernl adds\n * `apps`, the tier that serves applet manifests. The configuration is persisted\n * at `kernl:relays:v1` and `changes$` replays the current value to new\n * subscribers so UI and adapters can share one source.\n *\n * @param storage - Where the user's relay choices are persisted.\n * @param defaults - Per-tier overrides applied over {@link DEFAULT_RELAY_TIERS} when nothing is persisted.\n * @returns The tier configuration.\n * @example\n * ```ts\n * const tiers = createRelayTiers(localStorage, { apps: ['wss://relay.example'] });\n * tiers.add('outbox', 'wss://relay.mine');\n * tiers.get().outbox; // ['wss://relay.mine']\n * ```\n */\nexport function createRelayTiers(storage: StorageLike, defaults: Partial<Record<RelayTier, readonly string[]>> = {}): RelayTiers {\n const store = createNamespacedStore(storage, 'kernl');\n const persisted = store.getJson<Partial<Record<RelayTier, readonly string[]>> | null>(STORAGE_KEY, null);\n const initial = persisted ? merge(DEFAULT_RELAY_TIERS, persisted) : merge(DEFAULT_RELAY_TIERS, defaults);\n const changes$ = new BehaviorSubject<TierMap>(initial);\n\n const update = (tier: RelayTier, urls: readonly string[]): void => {\n const next = freeze({ ...changes$.value, [tier]: urls });\n store.setJson(STORAGE_KEY, next);\n changes$.next(next);\n };\n\n return {\n get: () => changes$.value,\n add(tier, url) {\n assertRelayUrl(url);\n const current = changes$.value[tier];\n if (!current.includes(url)) update(tier, [...current, url]);\n },\n set(tier, urls) {\n urls.forEach(assertRelayUrl);\n const next = [...new Set(urls)];\n const current = changes$.value[tier];\n if (next.length !== current.length || next.some((url, index) => url !== current[index])) update(tier, next);\n },\n remove(tier, url) {\n const current = changes$.value[tier];\n if (current.includes(url)) update(tier, current.filter((entry) => entry !== url));\n },\n changes$,\n };\n}\n","import { normalizeRelayUrl } from 'applesauce-core/helpers';\n\n/** What came of one publish across several servers. */\nexport interface PublishOutcome {\n /** Servers that accepted the event, normalised, in the order they answered. */\n readonly accepted: readonly string[];\n /** Servers that refused it, each with the server's own reason or `refused`. */\n readonly refused: readonly { url: string; reason: string }[];\n /** True when at least one server accepted it (D-028). */\n readonly ok: boolean;\n}\n\n/** One server's answer, as applesauce-relay's `PublishResponse` carries it. */\nexport interface PublishAnswer {\n readonly ok: boolean;\n readonly from: string;\n readonly message?: string;\n}\n\n/**\n * The server URL in its normalised form, or as given when it is not a server URL.\n *\n * @param url - A server URL as written anywhere.\n * @returns The normalised URL, or `url` unchanged.\n * @example\n * ```ts\n * relayKey('wss://Relay.Example'); // 'wss://relay.example/'\n * relayKey('not a server'); // 'not a server'\n * ```\n */\nexport function relayKey(url: string): string {\n return toRelayUrl(url) ?? url;\n}\n\n/**\n * A server URL in its normalised form, when it is one. Only `ws:` and `wss:`\n * count: applesauce's normaliser would turn `https://` or a bare word into a\n * server address, and NIP-66 lets a report name a server by pubkey.\n *\n * @param url - A server URL as written anywhere.\n * @returns The normalised URL, or undefined.\n * @example\n * ```ts\n * toRelayUrl('wss://Relay.Example'); // 'wss://relay.example/'\n * toRelayUrl('https://relay.example'); // undefined\n * ```\n */\nexport function toRelayUrl(url: string): string | undefined {\n if (!/^wss?:\\/\\//i.test(url.trim())) return undefined;\n try {\n return normalizeRelayUrl(url);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Normalise a list of server URLs, dropping duplicates and anything that is not a server URL.\n *\n * @param urls - Server URLs as written anywhere.\n * @returns The normalised URLs, first occurrence first.\n * @example\n * ```ts\n * relayUrls(['wss://a.example', 'wss://A.example/', 'https://b.example']); // ['wss://a.example/']\n * ```\n */\nexport function relayUrls(urls: Iterable<string>): string[] {\n const seen = new Set<string>();\n for (const url of urls) {\n const normalized = toRelayUrl(url);\n if (normalized) seen.add(normalized);\n }\n return [...seen];\n}\n\n/**\n * Fold the servers' answers to one publish into an outcome. A server that\n * answered more than once counts once, and an acceptance wins over a refusal,\n * because the event is on that server either way.\n *\n * @param responses - The answers `RelayPool.publish` resolved with.\n * @returns Who accepted, who refused and why, and whether anyone accepted.\n * @example\n * ```ts\n * const outcome = summarizePublish(await pool.publish(relays, event));\n * outcome.ok; // true when 2 of 3 accepted\n * ```\n */\nexport function summarizePublish(responses: readonly PublishAnswer[]): PublishOutcome {\n const accepted: string[] = [];\n const refused = new Map<string, string>();\n for (const response of responses) {\n const url = relayKey(response.from);\n if (accepted.includes(url)) continue;\n if (response.ok) {\n accepted.push(url);\n refused.delete(url);\n } else {\n refused.set(url, response.message || 'refused');\n }\n }\n return {\n accepted,\n refused: [...refused].map(([url, reason]) => ({ url, reason })),\n ok: accepted.length > 0,\n };\n}\n\n/**\n * Say what came of a publish in words for the person. The sentence never\n * repeats a server's reason, which is written for developers and often names\n * the protocol.\n *\n * @param outcome - The result of {@link summarizePublish}.\n * @returns A sentence such as `Saved to 2 of 3 servers` or `No server accepted it`.\n * @example\n * ```ts\n * describeOutcome({ accepted: ['wss://a/'], refused: [{ url: 'wss://b/', reason: 'blocked' }], ok: true });\n * // 'Saved to 1 of 2 servers'\n * ```\n */\nexport function describeOutcome(outcome: PublishOutcome): string {\n const total = outcome.accepted.length + outcome.refused.length;\n if (total === 0) return 'There was no server to save it to';\n if (!outcome.ok) return 'No server accepted it';\n if (outcome.refused.length > 0) return `Saved to ${outcome.accepted.length} of ${total} servers`;\n return total === 1 ? 'Saved to 1 server' : `Saved to all ${total} servers`;\n}\n","import { auditTime, BehaviorSubject, isObservable, map, Subject, type Observable, type Subscription } from 'rxjs';\nimport type { RelayPool } from 'applesauce-relay';\nimport type { NostrEvent } from 'applesauce-core/helpers';\nimport {\n RELAY_DISCOVERY_KIND,\n getRelayDiscoveryAcceptedKinds,\n getRelayDiscoveryNetworkType,\n getRelayDiscoveryRequirements,\n getRelayDiscoveryRTT,\n getRelayDiscoverySupportedNIPs,\n getRelayDiscoveryTypes,\n getRelayDiscoveryURL,\n} from 'applesauce-common/helpers';\nimport { relayUrls, toRelayUrl } from './publish-outcome.js';\n\n/**\n * Servers that carry NIP-66 monitors' reports: the ones nostr.watch's own\n * client reads. Its history server is left out: its certificate does not\n * match its name, so a browser refuses it.\n *\n * @example\n * ```ts\n * createRelayDirectory({ pool, relays: DEFAULT_MONITOR_RELAYS });\n * ```\n */\nexport const DEFAULT_MONITOR_RELAYS: readonly string[] = Object.freeze([\n 'wss://relay.nostr.watch',\n 'wss://relaypag.es',\n 'wss://monitorlizard.nostr1.com',\n]);\n\n/** What a suggestion is for: where the account is reached, where it writes, or where accounts' lists are looked up. */\nexport type SuggestPurpose = 'inbox' | 'outbox' | 'lookup';\n\n/**\n * What the directory suggests when it knows nothing, per purpose. General\n * servers for inbox and outbox; servers that index profiles and server lists\n * for lookup.\n *\n * @example\n * ```ts\n * DEFAULT_SUGGESTIONS.lookup; // ['wss://purplepag.es', 'wss://user.kindpag.es', 'wss://indexer.coracle.social']\n * ```\n */\nexport const DEFAULT_SUGGESTIONS: Readonly<Record<SuggestPurpose, readonly string[]>> = Object.freeze({\n inbox: Object.freeze(['wss://relay.damus.io', 'wss://nos.lol', 'wss://relay.primal.net']),\n outbox: Object.freeze(['wss://relay.damus.io', 'wss://nos.lol', 'wss://relay.primal.net']),\n lookup: Object.freeze(['wss://purplepag.es', 'wss://user.kindpag.es', 'wss://indexer.coracle.social']),\n});\n\n/** One server as the monitors that watch it describe it. */\nexport interface RelayListing {\n /** The normalised server URL. */\n readonly url: string;\n /** How many distinct monitors reported on it within the directory's window. */\n readonly monitors: number;\n /** The newest report's `created_at`, in seconds. */\n readonly lastSeen: number;\n /** Mean connection time in milliseconds across the monitors that measured it. */\n readonly rttOpen?: number;\n /** Mean read time in milliseconds. */\n readonly rttRead?: number;\n /** Mean write time in milliseconds. */\n readonly rttWrite?: number;\n /** The newest report's network, such as `clearnet`. */\n readonly network?: string;\n /** Every NIP any monitor saw it support, ascending. */\n readonly nips: readonly number[];\n /** Every server type any monitor gave it, such as `PublicOutbox`. */\n readonly types: readonly string[];\n /** The newest report says it requires a login. */\n readonly requiresAuth: boolean;\n /** The newest report says it requires payment. */\n readonly requiresPayment: boolean;\n /** The newest report says it accepts writes only from some accounts. */\n readonly restrictedWrites: boolean;\n}\n\n/** Options for {@link RelayDirectory.suggest}. */\nexport interface SuggestOptions {\n readonly purpose: SuggestPurpose;\n /** Servers already chosen, left out of the answer. */\n readonly exclude?: readonly string[];\n /** How many to suggest; 3 by default, the middle of NIP-65's 2–4. */\n readonly limit?: number;\n}\n\n/** A live directory of monitored servers. */\nexport interface RelayDirectory {\n /** Every listing, best first, replayed to new subscribers and re-emitted at most every `throttleMs` while reports stream in. */\n readonly listings$: Observable<readonly RelayListing[]>;\n /** The listings as of now, best first. */\n listings(): readonly RelayListing[];\n /** Listings whose address matches what the person typed, best first. */\n search(text: string, limit?: number): readonly RelayListing[];\n /** Servers to suggest for a purpose: the well-known fallback first, unless monitors say it refuses, then durable hosts from the directory. */\n suggest(options: SuggestOptions): readonly RelayListing[];\n /** Open the streaming subscription. Does nothing when already open. */\n start(): void;\n /** Close it, keeping what was learned. */\n stop(): void;\n}\n\n/** The pool surface the directory needs. */\nexport type DirectoryPool = Pick<RelayPool, 'subscription'>;\n\n/** Options for {@link createRelayDirectory}. */\nexport interface RelayDirectoryOptions {\n readonly pool: DirectoryPool;\n /** Servers to read reports from; {@link DEFAULT_MONITOR_RELAYS} by default. */\n readonly relays?: readonly string[] | Observable<readonly string[]>;\n /** How old a report may be, in seconds; two days by default. */\n readonly maxAgeSeconds?: number;\n /** The clock, in seconds. */\n readonly now?: () => number;\n /** What to suggest when the directory knows too few: one list for every purpose, or one per purpose. {@link DEFAULT_SUGGESTIONS} by default. */\n readonly fallback?: readonly string[] | Partial<Readonly<Record<SuggestPurpose, readonly string[]>>>;\n /** The least time between two emissions of `listings$`, in milliseconds; 250 by default. */\n readonly throttleMs?: number;\n}\n\ninterface Built {\n readonly listings: readonly RelayListing[];\n readonly indexers: ReadonlySet<string>;\n}\n\nconst TWO_DAYS = 2 * 24 * 60 * 60;\nconst HOUR = 3600;\nconst DEFAULT_LIMIT = 3;\nconst INDEX_KINDS = new Set(['0', '10002']);\n\nfunction mean(values: readonly (number | undefined)[]): number | undefined {\n const known = values.filter((value): value is number => value !== undefined && Number.isFinite(value));\n return known.length === 0 ? undefined : known.reduce((sum, value) => sum + value, 0) / known.length;\n}\n\nfunction openTime(listing: RelayListing): number {\n return listing.rttOpen ?? Infinity;\n}\n\nfunction byRtt(a: RelayListing, b: RelayListing): number {\n return openTime(a) - openTime(b);\n}\n\n/** Seen by more monitors first, then seen within a more recent hour, then quicker to connect. */\nfunction rank(a: RelayListing, b: RelayListing): number {\n return b.monitors - a.monitors || Math.floor(b.lastSeen / HOUR) - Math.floor(a.lastSeen / HOUR) || byRtt(a, b) || a.url.localeCompare(b.url);\n}\n\nfunction listingFrom(url: string, reports: readonly NostrEvent[]): RelayListing {\n const newest = reports.reduce((best, event) => (event.created_at > best.created_at ? event : best));\n const requirements = getRelayDiscoveryRequirements(newest);\n const nips = new Set(reports.flatMap(getRelayDiscoverySupportedNIPs).map(Number).filter(Number.isInteger));\n const measured = {\n rttOpen: mean(reports.map((event) => getRelayDiscoveryRTT(event, 'open'))),\n rttRead: mean(reports.map((event) => getRelayDiscoveryRTT(event, 'read'))),\n rttWrite: mean(reports.map((event) => getRelayDiscoveryRTT(event, 'write'))),\n network: getRelayDiscoveryNetworkType(newest),\n };\n const known = Object.fromEntries(Object.entries(measured).filter(([, value]) => value !== undefined)) as Pick<RelayListing, keyof typeof measured>;\n return {\n url,\n monitors: reports.length,\n lastSeen: newest.created_at,\n ...known,\n nips: [...nips].sort((a, b) => a - b),\n types: [...new Set(reports.flatMap(getRelayDiscoveryTypes))],\n requiresAuth: requirements.includes('auth'),\n requiresPayment: requirements.includes('payment'),\n restrictedWrites: requirements.includes('writes'),\n };\n}\n\nfunction isIndexer(listing: RelayListing, reports: readonly NostrEvent[]): boolean {\n if (listing.nips.includes(65)) return true;\n if (listing.types.some((type) => type.toLowerCase().includes('indexer'))) return true;\n return reports.some((event) => getRelayDiscoveryAcceptedKinds(event).some((kind) => INDEX_KINDS.has(kind)));\n}\n\nfunction blocks(listing: RelayListing | undefined, purpose: SuggestPurpose): boolean {\n if (!listing) return false;\n if (listing.requiresAuth || listing.requiresPayment) return true;\n return purpose !== 'lookup' && listing.restrictedWrites;\n}\n\n/** Hosts that come and go: tunnels, private networks and test domains. A server there makes a poor home for an inbox. */\nconst PASSING_HOSTS = /(?:^|\\.)(?:trycloudflare\\.com|ngrok(?:-free)?\\.(?:app|io|dev)|loca\\.lt|ts\\.net|local|localhost|onion)$/i;\n\n/**\n * Whether a server is one to suggest: a named host on the default port at the\n * root, not a tunnel, a bare address or one path of a multi-purpose server.\n * Typed addresses are never held to this; it only shapes suggestions.\n */\nfunction isDurable(url: string): boolean {\n const { hostname, port, pathname } = new URL(url);\n return port === '' && pathname === '/' && !PASSING_HOSTS.test(hostname) && !/^[\\d.]+$|:/.test(hostname);\n}\n\nfunction placeholder(url: string): RelayListing {\n return { url, monitors: 0, lastSeen: 0, nips: [], types: [], requiresAuth: false, requiresPayment: false, restrictedWrites: false };\n}\n\nfunction fallbackFor(fallback: RelayDirectoryOptions['fallback'], purpose: SuggestPurpose): string[] {\n if (Array.isArray(fallback)) return relayUrls(fallback);\n const lists = (fallback ?? {}) as Partial<Record<SuggestPurpose, readonly string[]>>;\n return relayUrls(lists[purpose] ?? DEFAULT_SUGGESTIONS[purpose]);\n}\n\ninterface Query {\n readonly text: string;\n /** The person typed a scheme, so they are typing the address from its start. */\n readonly anchored: boolean;\n}\n\nfunction parseQuery(raw: string): Query {\n const lower = raw.trim().toLowerCase();\n const text = lower.replace(/^wss?:\\/\\//, '').replace(/\\/+$/, '');\n return { text, anchored: text !== lower.replace(/\\/+$/, '') };\n}\n\n/** 3 when the text starts the name a person knows the server by, 2 when it starts the address or one of its words, 1 when it appears inside, 0 otherwise. */\nfunction matchScore(url: string, query: Query): number {\n const address = url.replace(/^wss?:\\/\\//, '').replace(/\\/$/, '');\n if (!query.anchored && address.replace(/^(?:relay|nostr)\\./, '').startsWith(query.text)) return 3;\n if (address.startsWith(query.text)) return 2;\n if (query.anchored) return 0;\n if (address.split(/[.\\-/]/).some((word) => word.startsWith(query.text))) return 2;\n return address.includes(query.text) ? 1 : 0;\n}\n\n/**\n * Create a directory of servers from NIP-66 monitors' reports (kind 30166).\n *\n * `start()` streams reports newer than `maxAgeSeconds` for the `clearnet`\n * network from the monitor servers; a browser cannot dial the other networks,\n * and NIP-66 says a report SHOULD carry its network, so the filter asks the\n * servers to leave the rest out. A server that ignores the filter is\n * re-checked here: a report naming another network is dropped, one naming none\n * is kept. Each monitor's newest report per server counts; listings fold them\n * across monitors. NIP-66 warns that a monitor may be wrong or hostile, so the\n * directory only ranks, completes and suggests: it never removes a server the\n * person chose, and with no report at all `suggest` answers from the fallback\n * (D-029).\n *\n * @param options - The pool, the monitor servers, the window, the clock and the fallback.\n * @returns A directory; call `start()` to begin streaming.\n * @example\n * ```ts\n * const directory = createRelayDirectory({ pool });\n * directory.start();\n * directory.search('damus');\n * directory.suggest({ purpose: 'inbox', exclude: current });\n * ```\n */\nexport function createRelayDirectory(options: RelayDirectoryOptions): RelayDirectory {\n const now = options.now ?? (() => Math.floor(Date.now() / 1000));\n const maxAge = options.maxAgeSeconds ?? TWO_DAYS;\n const reports = new Map<string, Map<string, NostrEvent>>();\n const changed = new Subject<void>();\n let built: (Built & { readonly cutoff: number }) | undefined;\n let subscription: Subscription | undefined;\n\n function build(cutoff: number): Built & { readonly cutoff: number } {\n const listings: RelayListing[] = [];\n const indexers = new Set<string>();\n for (const [url, byMonitor] of reports) {\n const fresh = [...byMonitor.values()].filter((event) => event.created_at >= cutoff);\n if (fresh.length === 0) continue;\n const listing = listingFrom(url, fresh);\n listings.push(listing);\n if (isIndexer(listing, fresh)) indexers.add(url);\n }\n return { listings: listings.sort(rank), indexers, cutoff };\n }\n\n const current = (): Built => {\n const cutoff = now() - maxAge;\n if (built?.cutoff !== cutoff) built = build(cutoff);\n return built;\n };\n const listings$ = new BehaviorSubject<readonly RelayListing[]>([]);\n changed.pipe(auditTime(options.throttleMs ?? 250)).subscribe(() => listings$.next(current().listings));\n\n function ingest(event: NostrEvent): void {\n if (event.kind !== RELAY_DISCOVERY_KIND || event.created_at < now() - maxAge) return;\n const network = getRelayDiscoveryNetworkType(event);\n const url = toRelayUrl(getRelayDiscoveryURL(event) ?? '');\n if ((network !== undefined && network !== 'clearnet') || url === undefined) return;\n const byMonitor = reports.get(url) ?? new Map<string, NostrEvent>();\n const previous = byMonitor.get(event.pubkey);\n if (previous && previous.created_at >= event.created_at) return;\n byMonitor.set(event.pubkey, event);\n reports.set(url, byMonitor);\n built = undefined;\n changed.next();\n }\n\n function monitorRelays(): string[] | Observable<string[]> {\n const relays = options.relays ?? DEFAULT_MONITOR_RELAYS;\n return isObservable(relays) ? relays.pipe(map((list) => [...list])) : [...relays];\n }\n\n function suggest({ purpose, exclude = [], limit = DEFAULT_LIMIT }: SuggestOptions): readonly RelayListing[] {\n const { listings, indexers } = current();\n const skip = new Set(relayUrls(exclude));\n const known = new Map(listings.map((listing) => [listing.url, listing]));\n // Well-known servers come first unless a monitor says they now refuse; the directory fills the rest with durable hosts.\n const trusted = fallbackFor(options.fallback, purpose)\n .filter((url) => !skip.has(url) && !blocks(known.get(url), purpose))\n .map((url) => known.get(url) ?? placeholder(url));\n const taken = new Set(trusted.map((listing) => listing.url));\n const found = listings.filter(\n (listing) => !skip.has(listing.url) && !taken.has(listing.url) && !blocks(listing, purpose) && isDurable(listing.url) && (purpose !== 'lookup' || indexers.has(listing.url)),\n );\n return [...trusted, ...found].slice(0, limit);\n }\n\n return {\n listings$: listings$.asObservable(),\n listings: () => current().listings,\n search(text, limit = 10) {\n const query = parseQuery(text);\n return current()\n .listings.map((listing) => ({ listing, score: matchScore(listing.url, query) }))\n .filter((entry) => entry.score > 0)\n .sort((a, b) => b.score - a.score || b.listing.monitors - a.listing.monitors || byRtt(a.listing, b.listing))\n .slice(0, limit)\n .map((entry) => entry.listing);\n },\n suggest,\n start() {\n if (subscription && !subscription.closed) return;\n const filter = { kinds: [RELAY_DISCOVERY_KIND], '#n': ['clearnet'], since: now() - maxAge };\n subscription = options.pool.subscription(monitorRelays(), [filter]).subscribe({\n next: ingest,\n error: () => undefined,\n });\n },\n stop() {\n subscription?.unsubscribe();\n subscription = undefined;\n },\n };\n}\n","import { BehaviorSubject, combineLatest, distinctUntilChanged, map, of, Observable, switchMap, timer, type Subscription } from 'rxjs';\nimport type { EventStore } from 'applesauce-core';\nimport type { RelayPool } from 'applesauce-relay';\nimport type { ISigner } from 'applesauce-signers';\nimport { unixNow, type NostrEvent } from 'applesauce-core/helpers';\nimport { subscribeWithEose } from '../applesauce/relay-hooks.js';\nimport { DEFAULT_SUGGESTIONS, type RelayDirectory } from './directory.js';\nimport { relayUrls, summarizePublish, toRelayUrl, type PublishAnswer, type PublishOutcome } from './publish-outcome.js';\n\n/** The NIP-65 relay list kind. */\nconst RELAY_LIST_KIND = 10002;\n/** The extreme cap on waiting for a lookup server that never finishes. */\nconst PATIENCE_MS = 15_000;\nconst SUGGESTED = 3;\n\n/** Where an account is reached (inboxes, NIP-65 `read`) and where it writes (outboxes, `write`). */\nexport interface Mailboxes {\n readonly inboxes: readonly string[];\n readonly outboxes: readonly string[];\n}\n\n/** The account's published list, as the shell knows it now. */\nexport type MailboxState =\n | { readonly status: 'loading' }\n | { readonly status: 'missing'; readonly suggested: Mailboxes }\n | { readonly status: 'found'; readonly mailboxes: Mailboxes; readonly event: NostrEvent };\n\n/** The active account's inbox and outbox. */\nexport interface AccountMailboxes {\n /** The state, replayed to new subscribers. */\n readonly state$: Observable<MailboxState>;\n /** The state as of now. */\n state(): MailboxState;\n /**\n * Publish a new list. Resolves with who accepted it; rejects with `denied:read-only` or `invalid:relay-url`.\n * `onProgress` hears the outcome so far each time a server answers, when the pool can report answers one by one.\n */\n save(next: Mailboxes, onProgress?: (sofar: PublishOutcome) => void): Promise<PublishOutcome>;\n}\n\n/** The signer surface saving needs. */\nexport type MailboxSigner = Pick<ISigner, 'getPublicKey' | 'signEvent'>;\n\n/** The pool surface the mailboxes need. */\nexport type MailboxPool = Pick<RelayPool, 'req' | 'publish'> & Partial<Pick<RelayPool, 'event'>>;\n\n/** Options for {@link createAccountMailboxes}. */\nexport interface AccountMailboxesOptions {\n /** The shell's event store; found and saved lists are added to it. */\n readonly store: EventStore;\n readonly pool: MailboxPool;\n /** The active account's public key; the lookup follows it and ends when it completes. */\n readonly pubkey$: Observable<string | undefined>;\n /** Servers that index accounts' lists, asked on every lookup and every save. */\n readonly lookupRelays: () => readonly string[];\n /** The active account's signer, when it can sign. */\n readonly signer: () => MailboxSigner | undefined;\n /** Suggestions for an account with no list; the built-in ones without it. */\n readonly directory?: RelayDirectory;\n /** How long to wait for a lookup server that never finishes; 15 s by default. */\n readonly patienceMs?: number;\n}\n\n/**\n * Read a NIP-65 list. An unmarked `r` tag is both an inbox and an outbox; a\n * tag with any other marker, or a value that is not a `ws:` or `wss:` URL, is\n * skipped. applesauce's `getInboxes` is not used because its URL check refuses\n * top-level domains longer than six letters.\n *\n * @param event - A kind 10002 event, or nothing.\n * @returns Normalised inboxes and outboxes; empty for no event.\n * @example\n * ```ts\n * mailboxesFromEvent({ ...event, tags: [['r', 'wss://a.example'], ['r', 'wss://b.example', 'read']] });\n * // { inboxes: ['wss://a.example/', 'wss://b.example/'], outboxes: ['wss://a.example/'] }\n * ```\n */\nexport function mailboxesFromEvent(event: NostrEvent | undefined): Mailboxes {\n const inboxes = new Set<string>();\n const outboxes = new Set<string>();\n for (const [name, value = '', marker] of event?.tags ?? []) {\n const url = toRelayUrl(value);\n if (name !== 'r' || !url || (marker !== undefined && marker !== 'read' && marker !== 'write')) continue;\n if (marker !== 'write') inboxes.add(url);\n if (marker !== 'read') outboxes.add(url);\n }\n return { inboxes: [...inboxes], outboxes: [...outboxes] };\n}\n\nfunction strictUrls(urls: readonly string[]): string[] {\n return relayUrls(\n urls.map((url) => {\n if (!toRelayUrl(url)) throw new Error('invalid:relay-url');\n return url;\n }),\n );\n}\n\n/**\n * The tags of the next NIP-65 list: one `r` tag per server, unmarked when it\n * is both an inbox and an outbox, then every tag of the previous list that is\n * not an `r` tag, so what other clients wrote is kept.\n *\n * @param mailboxes - The inboxes and outboxes to publish.\n * @param previous - The list being replaced, if any.\n * @returns The tags. Throws `invalid:relay-url` for an entry that is not a `ws:` or `wss:` URL.\n * @example\n * ```ts\n * mailboxTags({ inboxes: ['wss://a.example', 'wss://b.example'], outboxes: ['wss://a.example'] });\n * // [['r', 'wss://a.example/'], ['r', 'wss://b.example/', 'read']]\n * ```\n */\nexport function mailboxTags(mailboxes: Mailboxes, previous?: NostrEvent): string[][] {\n const inboxes = strictUrls(mailboxes.inboxes);\n const outboxes = strictUrls(mailboxes.outboxes);\n const tags = relayUrls([...inboxes, ...outboxes]).map((url) => {\n if (!outboxes.includes(url)) return ['r', url, 'read'];\n if (!inboxes.includes(url)) return ['r', url, 'write'];\n return ['r', url];\n });\n const kept = (previous?.tags ?? []).filter((tag) => tag[0] !== 'r').map((tag) => [...tag]);\n return [...tags, ...kept];\n}\n\nfunction suggestions(directory: RelayDirectory | undefined): Mailboxes {\n if (!directory) {\n const general = relayUrls(DEFAULT_SUGGESTIONS.inbox).slice(0, SUGGESTED);\n return { inboxes: general, outboxes: relayUrls(DEFAULT_SUGGESTIONS.outbox).slice(0, SUGGESTED) };\n }\n const urls = (purpose: 'inbox' | 'outbox'): string[] => directory.suggest({ purpose, limit: SUGGESTED }).map((listing) => listing.url);\n return { inboxes: urls('inbox'), outboxes: urls('outbox') };\n}\n\nfunction sameState(a: MailboxState, b: MailboxState): boolean {\n if (a.status === 'found' && b.status === 'found') return a.event.id === b.event.id;\n if (a.status === 'missing' && b.status === 'missing') return JSON.stringify(a.suggested) === JSON.stringify(b.suggested);\n return a.status === b.status;\n}\n\n/** Becomes true once every lookup server has finished, or once the cap passes. */\nfunction lookupFinished(options: AccountMailboxesOptions, pubkey: string): Observable<boolean> {\n return new Observable<boolean>((observer) => {\n observer.next(false);\n const finish = (): void => observer.next(true);\n const cap: Subscription = timer(options.patienceMs ?? PATIENCE_MS).subscribe(finish);\n const lookup = subscribeWithEose(options.pool, relayUrls(options.lookupRelays()), [{ kinds: [RELAY_LIST_KIND], authors: [pubkey] }], (item) => {\n if (item === 'EOSE') finish();\n else options.store.add(item as NostrEvent);\n });\n return () => {\n cap.unsubscribe();\n lookup.unsubscribe();\n };\n }).pipe(distinctUntilChanged());\n}\n\nfunction stateFor(options: AccountMailboxesOptions, pubkey: string | undefined): Observable<MailboxState> {\n if (pubkey === undefined) return of({ status: 'loading' });\n const listings$ = options.directory?.listings$ ?? of([]);\n return combineLatest([options.store.replaceable(RELAY_LIST_KIND, pubkey), lookupFinished(options, pubkey), listings$]).pipe(\n map(([event, finished]): MailboxState => {\n if (event) return { status: 'found', mailboxes: mailboxesFromEvent(event), event };\n if (!finished) return { status: 'loading' };\n return { status: 'missing', suggested: suggestions(options.directory) };\n }),\n );\n}\n\n/** Publish through the pool's per-server stream, reporting each answer; a server that never answers counts as refusing. */\nfunction publishStreaming(publish: NonNullable<MailboxPool['event']>, relays: string[], event: NostrEvent, onProgress: (sofar: PublishOutcome) => void): Promise<PublishOutcome> {\n const answers: PublishAnswer[] = [];\n return new Promise((resolve) => {\n const finish = (): void => {\n const silent = relays.filter((url) => !answers.some((answer) => answer.from === url));\n resolve(summarizePublish([...answers, ...silent.map((from) => ({ ok: false, from, message: 'no answer' }))]));\n };\n publish(relays, event).subscribe({\n next(answer) {\n answers.push(answer);\n onProgress(summarizePublish(answers));\n },\n error: finish,\n complete: finish,\n });\n });\n}\n\nasync function publishList(options: AccountMailboxesOptions, signer: MailboxSigner, next: Mailboxes, onProgress?: (sofar: PublishOutcome) => void): Promise<PublishOutcome> {\n const pubkey = await signer.getPublicKey();\n const previous = options.store.getReplaceable(RELAY_LIST_KIND, pubkey);\n const tags = mailboxTags(next, previous);\n const created_at = Math.max(unixNow(), (previous?.created_at ?? 0) + 1);\n const event = await signer.signEvent({ kind: RELAY_LIST_KIND, created_at, tags, content: previous?.content ?? '' });\n const old = mailboxesFromEvent(previous);\n // NIP-65: the list goes to where the account writes and is read, old and new, and to the indexers.\n const relays = relayUrls([...next.outboxes, ...old.outboxes, ...next.inboxes, ...options.lookupRelays()]);\n const stream = options.pool.event?.bind(options.pool);\n if (stream && onProgress) {\n // The list is shown as soon as one server holds it; the rest keep answering.\n const progress = (sofar: PublishOutcome): void => {\n if (sofar.ok) options.store.add(event);\n onProgress(sofar);\n };\n return publishStreaming(stream, relays, event, progress);\n }\n const outcome = await options.pool.publish(relays, event).then(summarizePublish, (error: unknown) => ({\n accepted: [],\n refused: relays.map((url) => ({ url, reason: String(error).replace(/^Error: /, '') })),\n ok: false,\n }));\n if (outcome.ok) options.store.add(event);\n return outcome;\n}\n\n/**\n * Watch the active account's NIP-65 list and save a new one.\n *\n * The list is streamed from `lookupRelays()` for whichever account `pubkey$`\n * names, added to the store, and kept open so a newer list from another\n * client replaces it; the store keeps the newest. The state is `loading`\n * until a list arrives or every server has finished, or failed, without one,\n * or `patienceMs` passes for a server that never answers; it is then\n * `missing` with suggestions from the directory. With nobody signed in it\n * stays `loading`. Saving signs the list with the active signer, publishes it\n * to the new outboxes, the old outboxes, the new inboxes and the lookup\n * servers, and succeeds when any of them accepts it (D-028). A list nobody\n * accepted is not added to the store, so the state never shows a list no\n * server holds.\n *\n * @param options - The store, pool, active account, lookup servers, signer and directory.\n * @returns The account's mailboxes.\n * @example\n * ```ts\n * const mailboxes = createAccountMailboxes({ store, pool, pubkey$, lookupRelays: () => tiers.get().discovery, signer });\n * mailboxes.state$.subscribe((state) => render(state));\n * const outcome = await mailboxes.save({ inboxes: ['wss://in.example'], outboxes: ['wss://out.example'] });\n * describeOutcome(outcome); // 'Saved to 3 of 4 servers'\n * ```\n */\nexport function createAccountMailboxes(options: AccountMailboxesOptions): AccountMailboxes {\n const state$ = new BehaviorSubject<MailboxState>({ status: 'loading' });\n options.pubkey$\n .pipe(switchMap((pubkey) => stateFor(options, pubkey)))\n .subscribe((state) => {\n if (!sameState(state$.value, state)) state$.next(state);\n });\n return {\n state$: state$.asObservable(),\n state: () => state$.value,\n async save(next, onProgress) {\n const signer = options.signer();\n if (!signer) throw new Error('denied:read-only');\n return publishList(options, signer, next, onProgress);\n },\n };\n}\n","import type { RelayPool, RelayPoolOptions } from 'applesauce-relay';\nimport { normalizeRelayUrl, type Filter } from 'applesauce-core/helpers';\nimport type { NappletMessageTarget, RelayPoolHooks, RelayPoolLike } from '@kehto/shell';\nimport type { NostrEvent, NostrFilter } from '@napplet/core';\nimport { NAPPLET_KINDS } from '@kehto/nip/5d';\nimport type { RelayTiers } from '../types.js';\n\n/** The slice of applesauce's `RelayPool` kernl adapts. Narrow so tests can supply a fake. */\nexport type ApplesaucePool = Pick<RelayPool, 'req' | 'request' | 'publish'>;\n\n/**\n * How the shell's own pool redials a relay that refused the connection.\n *\n * applesauce-relay 7.1 redials refused connections three times by default,\n * pausing one, two and three seconds, and a publish waits for every relay it\n * was sent to, so one dead relay in a tier held a publish for about six\n * seconds. One redial after a second keeps the case it exists for: a busy\n * public relay answers a websocket upgrade with 502 or 503 for a moment and\n * accepts the next one (D-025, D-037). Subscriptions keep applesauce's\n * default, because a live subscription should come back after a drop.\n *\n * @example\n * ```ts\n * const pool = new RelayPool(SHELL_RELAY_OPTIONS);\n * ```\n */\nexport const SHELL_RELAY_OPTIONS: RelayPoolOptions = Object.freeze({\n publishRetry: Object.freeze({ count: 1, delay: 1_000 }),\n requestReconnect: Object.freeze({ count: 1, delay: 1_000 }),\n});\n\n/** Replaceable kinds that live on the discovery tier. */\nconst DISCOVERY_KINDS: ReadonlySet<number> = new Set([0, 3, 10002]);\n/** Applet manifests and the legacy catalogue kind. */\nconst APP_KINDS: ReadonlySet<number> = new Set([...NAPPLET_KINDS, 32267]);\n\n/** A subscription that delivers events once each and signals the end of stored events. */\nexport interface EoseSubscription {\n unsubscribe(): void;\n}\n\n/**\n * View NAP filters as applesauce filters. The two types describe the same\n * NIP-01 object; applesauce adds an index signature for NIP-91 `&` tags that\n * the NAP type does not declare.\n *\n * @param filters - NAP filters.\n * @returns The same array typed for applesauce.\n * @example\n * ```ts\n * pool.request(relays, asFilters(filters));\n * ```\n */\nexport function asFilters(filters: NostrFilter[]): Filter[] {\n return filters as Filter[];\n}\n\n/**\n * Subscribe through the pool's raw `req` so the end of stored events is\n * observable: `EOSE` is reported once, after every relay has answered or\n * failed, and events are deduplicated by id because `req` does not.\n * applesauce's `subscription()` deduplicates but hides `EOSE`, which kehto's\n * relay service relies on to answer `relay.subscribe`.\n *\n * @param pool - The shared applesauce pool.\n * @param relays - Relay URLs to ask.\n * @param filters - Filters for the request.\n * @param callback - Receives each new event once, then `'EOSE'`.\n * @returns A handle that closes the subscription.\n * @example\n * ```ts\n * const sub = subscribeWithEose(pool, ['wss://relay.example'], [{ kinds: [1] }], (item) => {\n * if (item !== 'EOSE') console.log(item.id);\n * });\n * sub.unsubscribe();\n * ```\n */\nexport function subscribeWithEose(\n pool: Pick<ApplesaucePool, 'req'>,\n relays: string[],\n filters: NostrFilter[],\n callback: (item: NostrEvent | 'EOSE') => void,\n): EoseSubscription {\n const seen = new Set<string>();\n const waiting = new Set(relays.map(normalizeRelayUrl));\n let eoseSent = waiting.size === 0;\n if (eoseSent) callback('EOSE');\n const settle = (from: string): void => {\n waiting.delete(normalizeRelayUrl(from));\n if (eoseSent || waiting.size > 0) return;\n eoseSent = true;\n callback('EOSE');\n };\n const subscription = pool.req(relays, asFilters(filters)).subscribe((message) => {\n if (message.type === 'EVENT') {\n if (seen.has(message.event.id)) return;\n seen.add(message.event.id);\n callback(message.event as NostrEvent);\n return;\n }\n if (message.type !== 'OPEN') settle(message.from);\n });\n return { unsubscribe: () => subscription.unsubscribe() };\n}\n\n/**\n * Adapt the shared applesauce `RelayPool` to kehto's `RelayPoolLike`.\n *\n * @param pool - The one pool the shell owns (D-002).\n * @returns An object kehto's `RelayPoolHooks.getRelayPool` can return.\n * @example\n * ```ts\n * const like = createRelayPoolLike(pool);\n * like.subscription(['wss://relay.example'], [{ kinds: [1] }]).subscribe((item) => {});\n * ```\n */\nexport function createRelayPoolLike(pool: ApplesaucePool): RelayPoolLike {\n return {\n subscription(relayUrls, filters) {\n return {\n subscribe(observer) {\n return subscribeWithEose(pool, relayUrls, filters as NostrFilter[], observer);\n },\n };\n },\n request(relayUrls, filters) {\n return {\n subscribe(observer) {\n const subscription = pool.request(relayUrls, asFilters(filters as NostrFilter[])).subscribe({\n next: (event) => observer.next(event),\n complete: () => observer.complete(),\n error: () => observer.error(),\n });\n return { unsubscribe: () => subscription.unsubscribe() };\n },\n };\n },\n async publish(relayUrls, event) {\n await pool.publish(relayUrls, event as NostrEvent);\n },\n };\n}\n\nfunction kindsOf(filters: readonly NostrFilter[]): number[] | undefined {\n const kinds: number[] = [];\n for (const filter of filters) {\n if (!filter.kinds || filter.kinds.length === 0) return undefined;\n kinds.push(...filter.kinds);\n }\n return kinds;\n}\n\nfunction unique(urls: readonly string[]): string[] {\n return [...new Set(urls)];\n}\n\n/**\n * Choose the relay tier for a set of filters.\n *\n * Profiles, follow lists and relay lists come from the discovery tier; applet\n * manifests from the apps tier; everything else goes to the user's outbox\n * relays plus the super tier. A filter without kinds cannot be classified and\n * takes the general path.\n *\n * @param tiers - The current tier configuration.\n * @param filters - Filters about to be sent.\n * @returns Relay URLs, deduplicated.\n * @example\n * ```ts\n * selectRelayTier(tiers, [{ kinds: [0], authors: [pubkey] }]); // discovery, then outbox and super\n * ```\n */\nexport function selectRelayTier(tiers: RelayTiers, filters: readonly NostrFilter[]): string[] {\n const config = tiers.get();\n const kinds = kindsOf(filters);\n if (kinds && kinds.length > 0) {\n // Profiles, follows and relay lists live on indexers and on their authors' own servers (NIP-65), so both are asked.\n if (kinds.every((kind) => DISCOVERY_KINDS.has(kind))) return unique([...config.discovery, ...config.outbox, ...config.super]);\n if (kinds.every((kind) => APP_KINDS.has(kind))) return unique(config.apps);\n }\n return unique([...config.super, ...config.outbox]);\n}\n\n/**\n * Build kehto's `RelayPoolHooks` over the shared applesauce pool.\n *\n * Scoped relays (one relay per window, the NIP-29 pattern) are kept minimal:\n * one open subscription per window, replaced on reopen, and events delivered\n * to the window's bound port as `relay.event` envelopes.\n *\n * @param pool - The shared applesauce pool.\n * @param tiers - Relay tiers used for `selectRelayTier`.\n * @returns Hooks for `ShellAdapter.relayPool`.\n * @example\n * ```ts\n * const adapter: ShellAdapter = { relayPool: createRelayPoolHooks(pool, tiers), ... };\n * ```\n */\nexport function createRelayPoolHooks(pool: ApplesaucePool, tiers: RelayTiers): RelayPoolHooks {\n const like = createRelayPoolLike(pool);\n const tracked = new Map<string, () => void>();\n const scoped = new Map<string, { relayUrl: string; subscription: EoseSubscription }>();\n\n const closeScopedRelay = (windowId: string): void => {\n scoped.get(windowId)?.subscription.unsubscribe();\n scoped.delete(windowId);\n };\n\n return {\n getRelayPool: () => like,\n trackSubscription(subKey, cleanup) {\n tracked.get(subKey)?.();\n tracked.set(subKey, cleanup);\n },\n untrackSubscription(subKey) {\n tracked.get(subKey)?.();\n tracked.delete(subKey);\n },\n openScopedRelay(windowId: string, relayUrl: string, subId: string, filters: NostrFilter[], target: NappletMessageTarget) {\n closeScopedRelay(windowId);\n const subscription = subscribeWithEose(pool, [relayUrl], filters, (item) => {\n target.postMessage(item === 'EOSE' ? { type: 'relay.eose', subId } : { type: 'relay.event', subId, event: item });\n });\n scoped.set(windowId, { relayUrl, subscription });\n },\n closeScopedRelay,\n async publishToScopedRelay(windowId, event) {\n const entry = scoped.get(windowId);\n if (!entry) return false;\n try {\n const [response] = await pool.publish([entry.relayUrl], event);\n return response?.ok === true;\n } catch {\n return false;\n }\n },\n selectRelayTier: (filters) => selectRelayTier(tiers, filters),\n };\n}\n","import { lastValueFrom, toArray } from 'rxjs';\nimport { createRelayPoolService, type DmRelayPool, type RelayPoolServiceOptions } from '@kehto/services';\nimport type { RelayOperationPlan, RelayPlanningServiceHandler } from '@kehto/runtime';\nimport type { NappletMessage, NostrEvent, NostrFilter } from '@napplet/core';\nimport type { RelayTiers } from '../types.js';\nimport { asFilters, selectRelayTier, subscribeWithEose, type ApplesaucePool } from './relay-hooks.js';\n\n/** The relay-pool shape kehto's outbox router consumes. Declared structurally so core needs no extra import. */\nexport interface OutboxRelayPoolLike {\n subscribe(filters: NostrFilter[], relayUrls: string[], callback: (item: NostrEvent | 'EOSE') => void): { unsubscribe(): void };\n publish(event: NostrEvent, relayUrls: string[]): Promise<Record<string, boolean>>;\n isAvailable(): boolean;\n}\n\n/**\n * Publish to every relay and succeed when any one accepts. A relay that refuses\n * or is unreachable is normal on an open network; only when none accepted is\n * the publish a failure, and then the reason names how many were tried (D-028).\n *\n * @param pool - The shared applesauce pool.\n * @param relays - Where to publish.\n * @param event - The signed event.\n * @returns How many relays accepted it.\n * @example\n * ```ts\n * await publishAccepted(pool, ['wss://a', 'wss://b'], event); // 1 when only one accepted\n * ```\n */\nexport async function publishAccepted(pool: ApplesaucePool, relays: string[], event: NostrEvent): Promise<number> {\n const responses = relays.length > 0 ? await pool.publish(relays, event) : [];\n const accepted = responses.filter((response) => response.ok).length;\n if (accepted === 0) throw new Error(`unavailable:not-accepted:0/${relays.length}`);\n return accepted;\n}\n\nasync function publishTo(pool: ApplesaucePool, relays: string[], event: NostrEvent): Promise<Record<string, boolean>> {\n const responses = await pool.publish(relays, event);\n return Object.fromEntries(responses.map((response) => [response.from, response.ok]));\n}\n\n/**\n * Options for kehto's `createRelayPoolService` over the shared applesauce pool.\n *\n * Publishes go to the tier selected for the event's kind, so a profile update\n * lands on discovery relays and the user's own, and a note on the user's outbox\n * plus the super tier. A publish succeeds when any relay accepts it.\n *\n * @param pool - The shared applesauce pool.\n * @param tiers - Relay tiers used to route publishes and unhinted subscriptions.\n * @returns Options for `createRelayPoolService`.\n * @example\n * ```ts\n * runtime.registerService('relay', createRelayPoolService(createAppletRelayBackend(pool, tiers)));\n * ```\n */\nexport function createAppletRelayBackend(pool: ApplesaucePool, tiers: RelayTiers): RelayPoolServiceOptions {\n return {\n subscribe(filters, callback, relayUrls) {\n const relays = relayUrls ?? selectRelayTier(tiers, filters);\n return subscribeWithEose(pool, relays, filters, (item) => callback(item, relays));\n },\n async publish(event) {\n await publishAccepted(pool, selectRelayTier(tiers, [{ kinds: [event.kind] }]), event);\n },\n async publishToRelays(relayUrls, event) {\n await publishAccepted(pool, [...relayUrls], event);\n },\n selectRelayTier: (filters) => selectRelayTier(tiers, filters),\n isAvailable: () => true,\n };\n}\n\n/** A direct `handleMessage` call has no approval to lose, so its signal never aborts. */\nconst UNCANCELLED = new AbortController().signal;\n\nfunction kindOf(message: NappletMessage): number | undefined {\n const kind = (message as { event?: { kind?: unknown } }).event?.kind;\n return typeof kind === 'number' ? kind : undefined;\n}\n\n/**\n * kehto's relay service over the shared pool, with publishes planned by the\n * event's kind.\n *\n * kehto plans every relay operation before it runs and then publishes only to\n * the planned relays (`publishToRelays`), but its publish plan cannot see the\n * event. kernl's plan does, so a profile update is planned onto discovery\n * relays and the user's own, and a note onto the outbox plus the super tier,\n * as before. An applet's explicit relay hint is planned as kehto plans it.\n *\n * @param pool - The shared applesauce pool.\n * @param tiers - Relay tiers used to route publishes and unhinted subscriptions.\n * @returns The `relay` service handler.\n * @example\n * ```ts\n * registry.relay = createAppletRelayService(pool, tiers);\n * registry.relay.planRelayOperation('w1', { type: 'relay.publish', id: '1', event: { kind: 0 } }).relayUrls;\n * ```\n */\nexport function createAppletRelayService(pool: ApplesaucePool, tiers: RelayTiers): RelayPlanningServiceHandler {\n const inner = createRelayPoolService(createAppletRelayBackend(pool, tiers));\n function planRelayOperation(windowId: string, message: NappletMessage): RelayOperationPlan {\n const plan = inner.planRelayOperation(windowId, message);\n const kind = kindOf(message);\n const relay = (message as { relay?: unknown }).relay;\n const hinted = typeof relay === 'string' && relay.length > 0;\n if (plan.operation === 'subscribe' || plan.operation === 'query' || hinted || kind === undefined) return plan;\n const relayUrls = Object.freeze([...new Set(selectRelayTier(tiers, [{ kinds: [kind] }]))]);\n return Object.freeze({ operation: plan.operation, relayUrls, localOnly: relayUrls.length === 0 });\n }\n return {\n ...inner,\n planRelayOperation,\n handleMessage(windowId, message, send) {\n inner.executeRelayOperation(windowId, message, planRelayOperation(windowId, message), UNCANCELLED, send);\n },\n };\n}\n\n/**\n * The relay pool a messaging backend reads and writes through, satisfying\n * kehto's `DmRelayPool` over the same shared applesauce pool.\n *\n * @param pool - The shared applesauce pool.\n * @param tiers - Relay tiers used when a caller names no relays.\n * @returns A `DmRelayPool`.\n * @example\n * ```ts\n * const dmPool = createDmRelayPool(pool, tiers);\n * const history = await dmPool.query([{ kinds: [1059], '#p': [me] }]);\n * ```\n */\nexport function createDmRelayPool(pool: ApplesaucePool, tiers: RelayTiers): DmRelayPool {\n return {\n subscribe(filters, callback, relayUrls) {\n return subscribeWithEose(pool, relayUrls ?? selectRelayTier(tiers, filters), filters, callback);\n },\n async publish(event) {\n await publishAccepted(pool, selectRelayTier(tiers, [{ kinds: [event.kind] }]), event);\n },\n query(filters, relayUrls) {\n return lastValueFrom(pool.request(relayUrls ?? selectRelayTier(tiers, filters), asFilters(filters)).pipe(toArray()));\n },\n selectRelayTier: (filters) => selectRelayTier(tiers, filters),\n isAvailable: () => true,\n };\n}\n\n/**\n * The relay pool kehto's `createRelayPoolOutboxRouter` fans out through.\n *\n * @param pool - The shared applesauce pool.\n * @returns A pool with per-relay publish outcomes.\n * @example\n * ```ts\n * const router = createRelayPoolOutboxRouter({ relayPool: createOutboxRelayPool(pool), ... });\n * ```\n */\nexport function createOutboxRelayPool(pool: ApplesaucePool): OutboxRelayPoolLike {\n return {\n subscribe: (filters, relayUrls, callback) => subscribeWithEose(pool, relayUrls, filters, callback),\n publish: (event, relayUrls) => publishTo(pool, relayUrls, event),\n isAvailable: () => true,\n };\n}\n","import type { AccountManager, IAccount } from 'applesauce-accounts';\nimport type { AuthHooks } from '@kehto/shell';\nimport type { Signer } from '@kehto/runtime';\nimport type { SigningConsent } from '../consent/handler.js';\n\n/** Account types whose signer cannot sign. Mirrors `ReadonlyAccount.type` without importing the class. */\nconst READ_ONLY_TYPES: ReadonlySet<string> = new Set(['readonly']);\n\n/**\n * Whether an account can only show an identity, never sign for it.\n *\n * @param account - Any applesauce account.\n * @returns True for read-only accounts.\n * @example\n * ```ts\n * isReadOnlyAccount(ReadonlyAccount.fromPubkey(pubkey)); // true\n * ```\n */\nexport function isReadOnlyAccount(account: IAccount): boolean {\n return READ_ONLY_TYPES.has(account.type);\n}\n\n/**\n * Wrap an account as the NIP-07-shaped signer kehto expects.\n *\n * The account itself is never handed over: kehto sees four methods and the\n * encryption namespaces the account exposes, nothing that reveals key material.\n *\n * @param account - The active applesauce account.\n * @returns A kehto `Signer`.\n * @example\n * ```ts\n * const signer = wrapAccountSigner(account);\n * await signer.signEvent?.(template);\n * ```\n */\nexport function wrapAccountSigner(account: IAccount): Signer {\n const signer: Signer = {\n getPublicKey: () => account.getPublicKey(),\n signEvent: (template) => account.signEvent(template),\n };\n if (account.nip04) signer.nip04 = account.nip04;\n if (account.nip44) signer.nip44 = account.nip44;\n return signer;\n}\n\n/**\n * kehto `AuthHooks` over the applesauce `AccountManager`.\n *\n * `getSigner` returns null while nobody is signed in and for read-only accounts,\n * so the runtime refuses writes instead of failing inside a signer that throws.\n * When kehto names the requesting window, the signer it gets back puts every\n * `signEvent` through `consent` first, so a destructive write an applet asks\n * for is shown to the user and signed only on yes (kehto's runtime signs\n * applet publishes here and asks nobody). Without a window the shell is\n * signing for itself and the plain signer is returned.\n *\n * @param accounts - The shell's account manager.\n * @param consent - The gate from `createSigningConsent`.\n * @returns Hooks for `ShellAdapter.auth`.\n * @example\n * ```ts\n * const auth = createAuthHooks(accounts, consent);\n * auth.getUserPubkey(); // hex pubkey or null\n * await auth.getSigner('applet-1')?.signEvent?.(profileTemplate); // asks the user first\n * ```\n */\nexport function createAuthHooks(accounts: AccountManager, consent: SigningConsent): AuthHooks {\n // kehto's services compare the signer object at reply time with the one a\n // request started under, and drop the reply when it changed. One signer per\n // account and window keeps that comparison meaning \"the account changed\".\n const signers = new WeakMap<IAccount, Map<string | undefined, Signer>>();\n function build(account: IAccount, windowId: string | undefined): Signer {\n const signer = wrapAccountSigner(account);\n if (windowId === undefined) return signer;\n return {\n ...signer,\n async signEvent(template) {\n await consent(windowId, template);\n return account.signEvent(template);\n },\n } satisfies Signer;\n }\n return {\n getUserPubkey: () => accounts.active?.pubkey ?? null,\n getSigner(windowId?: string) {\n const account = accounts.active;\n if (!account || isReadOnlyAccount(account)) return null;\n const byWindow = signers.get(account) ?? new Map<string | undefined, Signer>();\n signers.set(account, byWindow);\n const signer = byWindow.get(windowId) ?? build(account, windowId);\n byWindow.set(windowId, signer);\n return signer;\n },\n };\n}\n","import { lastValueFrom, map } from 'rxjs';\nimport type { EventStore } from 'applesauce-core';\nimport { getContacts, getInboxes, getOutboxes, getProfileContent } from 'applesauce-core/helpers';\nimport { createAddressLoader, type AddressPointerLoader } from 'applesauce-loaders/loaders';\nimport type { CacheRequest } from 'applesauce-loaders';\nimport type { IdentityServiceOptions } from '@kehto/services';\nimport type { NostrEvent } from '@napplet/core';\nimport type { RelayTiers } from '../types.js';\nimport type { ApplesaucePool } from './relay-hooks.js';\n\n/** The profile shape NAP-IDENTITY returns for `identity.getProfile`. */\nexport interface IdentityProfile {\n name?: string;\n displayName?: string;\n about?: string;\n picture?: string;\n banner?: string;\n nip05?: string;\n lud16?: string;\n website?: string;\n}\n\n/** Read/write flags per relay URL, as `identity.getRelays` reports them. */\nexport type RelayPermissions = Record<string, { read: boolean; write: boolean }>;\n\n/** The host-backed lookups kehto's identity service accepts, plus the relay list for the signer wrapper. */\nexport interface IdentityProviders extends Pick<IdentityServiceOptions, 'getProfile' | 'getFollows' | 'getMutes' | 'getList' | 'getZaps' | 'getBlocked' | 'getBadges'> {\n getRelays(pubkey: string): Promise<RelayPermissions>;\n}\n\n/** Options for {@link createIdentityProviders}. */\nexport interface IdentityProviderOptions {\n /** Loads replaceable events the store does not hold yet. */\n readonly loader?: AddressPointerLoader;\n}\n\nconst PROFILE = 0;\nconst FOLLOWS = 3;\nconst MUTES = 10000;\nconst RELAYS = 10002;\n\nfunction profileFrom(event: NostrEvent): IdentityProfile | null {\n const content = getProfileContent(event);\n if (!content) return null;\n const profile: IdentityProfile = {};\n if (content.name) profile.name = content.name;\n if (content.display_name) profile.displayName = content.display_name;\n if (content.about) profile.about = content.about;\n if (content.picture) profile.picture = content.picture;\n if (content.banner) profile.banner = content.banner;\n if (content.nip05) profile.nip05 = content.nip05;\n if (content.lud16) profile.lud16 = content.lud16;\n if (content.website) profile.website = content.website;\n return profile;\n}\n\nfunction relaysFrom(event: NostrEvent): RelayPermissions {\n const inboxes = new Set(getInboxes(event));\n const outboxes = new Set(getOutboxes(event));\n const relays: RelayPermissions = {};\n for (const url of [...inboxes, ...outboxes]) relays[url] = { read: inboxes.has(url), write: outboxes.has(url) };\n return relays;\n}\n\nfunction mutedPubkeys(event: NostrEvent): string[] {\n return event.tags.filter((tag) => tag[0] === 'p' && typeof tag[1] === 'string').map((tag) => tag[1] as string);\n}\n\n/**\n * Where a replaceable event is looked up when its pointer names no relay:\n * the discovery tier first, then the general tier. Indexers hold most\n * profiles and lists, but not all; the general servers catch the rest.\n *\n * @param config - The current tiers.\n * @returns Deduplicated relay URLs.\n * @example\n * ```ts\n * lookupRelaysOf(tiers.get()); // ['wss://purplepag.es', 'wss://relay.nos.social', 'wss://relay.damus.io', …]\n * ```\n */\nexport function lookupRelaysOf(config: ReturnType<RelayTiers['get']>): string[] {\n return [...new Set([...config.discovery, ...config.super])];\n}\n\n/**\n * The applesauce address loader kernl uses for replaceable and addressable\n * events the store does not hold: it asks the pointer's relays, then the\n * discovery and general tiers, and adds what it finds to the store.\n *\n * @param store - The shell's single event store.\n * @param pool - The shared applesauce pool.\n * @param tiers - Relay tiers; discovery and general are the lookup fallback.\n * @param cacheRequest - Asked before any relay, so a cached event shows at once; the relays are still asked for newer.\n * @returns A loader for {@link createIdentityProviders} and `lookupReplaceable`.\n * @example\n * ```ts\n * const loader = createReplaceableLoader(eventStore, pool, tiers);\n * const lookupBefore = lookupReplaceable(eventStore, { loader, relays: () => tiers.get().outbox });\n * ```\n */\nexport function createReplaceableLoader(store: EventStore, pool: ApplesaucePool, tiers: RelayTiers, cacheRequest?: CacheRequest): AddressPointerLoader {\n return createAddressLoader((relays, filters) => pool.request(relays, filters), {\n eventStore: store,\n lookupRelays: tiers.changes$.pipe(map(lookupRelaysOf)),\n ...(cacheRequest ? { cacheRequest } : {}),\n });\n}\n\n/**\n * Host-backed identity lookups for kehto's `createIdentityService`.\n *\n * Profile, follows, relays and mutes are read from the shell's `EventStore`\n * and, on a miss, loaded once through an applesauce address loader that asks\n * the discovery and general tiers. Lists, zaps, blocked keys and badges return the\n * spec-shaped empty value: kernl does not claim data it has not fetched.\n *\n * @param store - The shell's single event store.\n * @param pool - The shared applesauce pool.\n * @param tiers - Relay tiers; discovery and general serve misses.\n * @param options - Loader override for tests.\n * @returns Lookup callbacks keyed as kehto's options expect.\n * @example\n * ```ts\n * const providers = createIdentityProviders(eventStore, pool, tiers);\n * runtime.registerService('identity', createIdentityService({ getSigner, ...providers }));\n * ```\n */\nexport function createIdentityProviders(store: EventStore, pool: ApplesaucePool, tiers: RelayTiers, options: IdentityProviderOptions = {}): IdentityProviders {\n const loader = options.loader ?? createReplaceableLoader(store, pool, tiers);\n\n async function replaceable(kind: number, pubkey: string): Promise<NostrEvent | undefined> {\n const cached = store.getReplaceable(kind, pubkey);\n if (cached) return cached;\n const loaded = await lastValueFrom(loader({ kind, pubkey, relays: lookupRelaysOf(tiers.get()) }), { defaultValue: undefined });\n return loaded ?? store.getReplaceable(kind, pubkey);\n }\n\n return {\n getProfile: async (pubkey) => {\n const event = await replaceable(PROFILE, pubkey);\n return event ? profileFrom(event) : null;\n },\n getFollows: async (pubkey) => {\n const event = await replaceable(FOLLOWS, pubkey);\n return event ? getContacts(event).map((pointer) => pointer.pubkey) : [];\n },\n getMutes: async (pubkey) => {\n const event = await replaceable(MUTES, pubkey);\n return event ? mutedPubkeys(event) : [];\n },\n getRelays: async (pubkey) => {\n const event = await replaceable(RELAYS, pubkey);\n return event ? relaysFrom(event) : {};\n },\n getList: () => [],\n getZaps: () => [],\n getBlocked: () => [],\n getBadges: () => [],\n };\n}\n","import { AccountManager, type IAccount, type SerializedAccount } from 'applesauce-accounts';\nimport { registerCommonAccountTypes } from 'applesauce-accounts/accounts';\nimport type { StorageLike } from '../types.js';\nimport { createNamespacedStore } from '../persistence/store.js';\n\nconst ACCOUNTS_KEY = 'accounts:v1';\nconst ACTIVE_KEY = 'active-account:v1';\n\n/**\n * Account types whose serialised form carries a raw secret. `PrivateKeyAccount`\n * serialises the key itself and `SeedWordsAccount` the mnemonic. Neither may be\n * added to a kernl account manager: the only persisted form of a local key is\n * applesauce's `PasswordAccount`, whose `ncryptsec` is NIP-49 encrypted.\n *\n * @example\n * ```ts\n * PLAINTEXT_KEY_ACCOUNT_TYPES.includes(account.type); // true for 'nsec' and 'seed-words'\n * ```\n */\nexport const PLAINTEXT_KEY_ACCOUNT_TYPES: readonly string[] = Object.freeze(['nsec', 'seed-words']);\n\n/**\n * An `AccountManager` that refuses accounts whose persistence would write a\n * plaintext key, and persists the rest to kernl's storage.\n *\n * @example\n * ```ts\n * const manager = new KernlAccountManager();\n * manager.addAccount(PasswordAccount.fromNcryptsec(pubkey, ncryptsec));\n * manager.addAccount(PrivateKeyAccount.fromKey(secretKey)); // throws 'denied:plaintext-key-persistence'\n * ```\n */\nexport class KernlAccountManager extends AccountManager {\n /**\n * Add an account, refusing plaintext-key types.\n *\n * @param account - The account to add.\n * @throws `denied:plaintext-key-persistence` for `PrivateKeyAccount` and `SeedWordsAccount`.\n */\n override addAccount(account: IAccount): void {\n if (PLAINTEXT_KEY_ACCOUNT_TYPES.includes(account.type)) throw new Error('denied:plaintext-key-persistence');\n super.addAccount(account);\n }\n}\n\nfunction restore(manager: AccountManager, accounts: SerializedAccount[], activeId: string | null): void {\n const safe = accounts.filter((entry) => !PLAINTEXT_KEY_ACCOUNT_TYPES.includes(entry.type));\n manager.fromJSON(safe, true);\n if (activeId && manager.getAccount(activeId)) manager.setActive(activeId);\n}\n\n/**\n * Create the shell's account manager with the common applesauce account types\n * registered, state restored from `kernl:accounts:v1` and\n * `kernl:active-account:v1`, and every later change persisted.\n *\n * Keys live only inside applesauce signer instances: a `PrivateKeyAccount` is\n * refused at `addAccount` with `denied:plaintext-key-persistence`, and any such\n * entry found in storage is dropped on restore. Wrap a local key as a\n * `PasswordAccount` before adding it.\n *\n * @param storage - Where accounts and the active id are persisted.\n * @returns The account manager.\n * @example\n * ```ts\n * const accounts = createKernlAccounts(localStorage);\n * accounts.addAccount(PasswordAccount.fromNcryptsec(pubkey, ncryptsec));\n * accounts.setActive(accounts.accounts[0]!);\n * ```\n */\nexport function createKernlAccounts(storage: StorageLike): AccountManager {\n const store = createNamespacedStore(storage, 'kernl');\n const manager = new KernlAccountManager();\n registerCommonAccountTypes(manager);\n restore(manager, store.getJson<SerializedAccount[]>(ACCOUNTS_KEY, []), store.getJson<string | null>(ACTIVE_KEY, null));\n\n manager.accounts$.subscribe(() => {\n store.setJson(ACCOUNTS_KEY, manager.toJSON(true));\n });\n manager.active$.subscribe((account) => {\n if (account) store.setJson(ACTIVE_KEY, account.id);\n else store.remove(ACTIVE_KEY);\n });\n return manager;\n}\n","import { decodeAddressPointer, decodeEventPointer } from 'applesauce-core/helpers';\nimport type { AppletPointer } from '../types.js';\nimport { decodeBuiltin } from './builtin.js';\n\nconst HEX_64 = /^[0-9a-f]{64}$/;\nconst COORDINATE = /^([0-9a-f]{64}):(\\d+):(.*)$/s;\nconst A_TAG_COORDINATE = /^(\\d+):([0-9a-f]{64}):(.*)$/s;\n/** An encoded address anywhere in the text, so one copied as a link or inside a sentence still opens. */\nconst ENCODED = /(?:naddr|nevent|note)1[02-9ac-hj-np-z]+/i;\n\nfunction invalid(): never {\n throw new Error('invalid:pointer');\n}\n\nfunction relays(hints: readonly string[] | undefined): readonly string[] {\n return Object.freeze([...(hints ?? [])]);\n}\n\nfunction fromCoordinate(pubkey: string, kind: string, identifier: string): AppletPointer {\n return { kind: 'address', pubkey, identifier, eventKind: Number(kind), relays: Object.freeze([]) };\n}\n\nfunction fromBech32(input: string): AppletPointer | undefined {\n if (input.startsWith('naddr1')) {\n const pointer = decodeAddressPointer(input);\n if (!pointer) invalid();\n return { kind: 'address', pubkey: pointer.pubkey, identifier: pointer.identifier, eventKind: pointer.kind, relays: relays(pointer.relays) };\n }\n if (input.startsWith('nevent1') || input.startsWith('note1')) {\n const pointer = decodeEventPointer(input);\n if (!pointer) invalid();\n return pointer.author\n ? { kind: 'event', id: pointer.id, relays: relays(pointer.relays), author: pointer.author }\n : { kind: 'event', id: pointer.id, relays: relays(pointer.relays) };\n }\n return undefined;\n}\n\n/**\n * Decode what a user typed or clicked into the event to fetch.\n *\n * Accepts `naddr1…`, `nevent1…`, `note1…`, a bare 64-hex event id, any of\n * those behind a `nostr:` prefix, and plain coordinates in either\n * `<pubkey>:<kind>:<identifier>` or NIP-01 `<kind>:<pubkey>:<identifier>`\n * order. An encoded address is also found inside a link or a sentence, since\n * that is how addresses are shared. The result says which event to fetch and\n * nothing more; trust comes from verifying that event, never from the pointer.\n *\n * @param input - The address text.\n * @returns The decoded pointer.\n * @throws `invalid:pointer` for anything else.\n * @example\n * ```ts\n * decodePointer('nostr:naddr1…').kind; // 'address'\n * decodePointer(`${pubkey}:35129:chat`); // { kind: 'address', pubkey, identifier: 'chat', eventKind: 35129, relays: [] }\n * decodePointer('https://applets.example/n/naddr1…?ref=share').kind; // 'address'\n * ```\n */\nexport function decodePointer(input: string): AppletPointer {\n const text = input.trim().replace(/^nostr:/i, '');\n const builtin = decodeBuiltin(text);\n if (builtin) return builtin;\n if (HEX_64.test(text)) return { kind: 'event', id: text, relays: Object.freeze([]) };\n\n const coordinate = COORDINATE.exec(text);\n if (coordinate) return fromCoordinate(coordinate[1] as string, coordinate[2] as string, coordinate[3] as string);\n const aTag = A_TAG_COORDINATE.exec(text);\n if (aTag) return fromCoordinate(aTag[2] as string, aTag[1] as string, aTag[3] as string);\n\n return fromBech32((ENCODED.exec(text)?.[0] ?? text).toLowerCase()) ?? invalid();\n}\n","import type { NappletManifest } from '@kehto/nip/5d';\nimport type { AppletPointer, AppletSummary, BuiltinApplet } from '../types.js';\nimport type { ResolvedApplet } from './resolve.js';\n\n/**\n * The key shown as the publisher of an applet nobody published. A manifest's catalogue id needs\n * a key, and the all-zero one cannot sign, so it can never collide with a real publisher.\n *\n * @example\n * ```ts\n * summary.builtin && summary.publisher === BUILTIN_PUBLISHER; // true\n * ```\n */\nexport const BUILTIN_PUBLISHER: string = '0'.repeat(64);\n\nconst ADDRESS = /^kernl:([a-z][a-z0-9-]*)$/;\nconst MANIFEST_KIND = 35129;\n\n/**\n * The address of an applet that comes with the shell.\n *\n * @param id - The built-in applet's name.\n * @returns `kernl:<id>`.\n * @example\n * ```ts\n * builtinAddress('messages'); // 'kernl:messages'\n * ```\n */\nexport function builtinAddress(id: string): string {\n return `kernl:${id}`;\n}\n\n/**\n * Read a `kernl:<id>` address.\n *\n * @param text - A trimmed address.\n * @returns A built-in pointer, or `undefined` when the text is not one.\n * @example\n * ```ts\n * decodeBuiltin('kernl:messages'); // { kind: 'builtin', id: 'messages', relays: [] }\n * ```\n */\nexport function decodeBuiltin(text: string): AppletPointer | undefined {\n const id = ADDRESS.exec(text)?.[1];\n return id === undefined ? undefined : { kind: 'builtin', id, relays: Object.freeze([]) };\n}\n\nasync function sha256Hex(text: string): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text));\n return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, '0')).join('');\n}\n\nfunction manifestOf(applet: BuiltinApplet): NappletManifest {\n const archetypes = (applet.archetypes ?? []).map((entry) => ({ slug: entry.slug, convention: entry.convention, params: [...(entry.params ?? [])] }));\n return {\n format: 'current',\n artifactHash: applet.sha256,\n optional: [...applet.optional],\n archetypeSlugs: [...new Set(archetypes.map((entry) => entry.slug))],\n intents: archetypes.map((entry) => ({ identity: entry.convention, parameters: entry.params })),\n kind: MANIFEST_KIND,\n pubkey: BUILTIN_PUBLISHER,\n dTag: applet.id,\n catalogId: `nip5d:${MANIFEST_KIND}:${BUILTIN_PUBLISHER}:${applet.id}`,\n paths: [{ path: '/index.html', sha256: applet.sha256 }],\n aggregateHash: applet.sha256,\n servers: [],\n requires: [...applet.requires],\n archetypes,\n title: applet.title,\n description: applet.description,\n };\n}\n\nfunction summaryOf(applet: BuiltinApplet): AppletSummary {\n const manifest = manifestOf(applet);\n return {\n identity: { dTag: applet.id, hash: applet.sha256 },\n address: builtinAddress(applet.id),\n title: applet.title,\n description: applet.description,\n publisher: BUILTIN_PUBLISHER,\n requires: Object.freeze([...applet.requires]),\n optional: Object.freeze([...applet.optional]),\n archetypes: Object.freeze([...(manifest.archetypeSlugs as string[])]),\n builtin: true,\n manifest,\n };\n}\n\n/**\n * Load an applet that comes with the shell and check it against its pinned hash.\n *\n * Nothing is fetched from the network and no signature is checked: the host that\n * lists the applet is the page the user already trusts with everything else, so\n * what it pins is as trusted as its own code. The check is that the bytes loaded\n * are the bytes pinned. The summary is shaped like a published applet's, so\n * grants, intents and the mount plan treat it the same.\n *\n * @param builtins - The applets the host ships.\n * @param id - The name from a `kernl:<id>` address.\n * @returns The summary and the verified `index.html`.\n * @throws `invalid:pointer` for a name the host does not ship, `unavailable:blob` when the\n * artifact cannot be loaded, `invalid:artifact-hash` when it does not match its pin.\n * @example\n * ```ts\n * const { summary, indexHtml } = await resolveBuiltin(builtins, 'messages');\n * summary.address; // 'kernl:messages'\n * ```\n */\nexport async function resolveBuiltin(builtins: readonly BuiltinApplet[], id: string): Promise<ResolvedApplet> {\n const applet = builtins.find((candidate) => candidate.id === id);\n if (!applet) throw new Error('invalid:pointer');\n const indexHtml = await applet.load().catch(() => {\n throw new Error('unavailable:blob');\n });\n if ((await sha256Hex(indexHtml)) !== applet.sha256) throw new Error('invalid:artifact-hash');\n return { summary: summaryOf(applet), indexHtml };\n}\n","import { filter, lastValueFrom, map, merge, switchMap, take, timer, toArray, type Observable, type OperatorFunction } from 'rxjs';\nimport {\n NappletResolutionError,\n openNappletArtifactCache,\n resolveNapplet,\n type NappletArtifactCache,\n type ResolveNappletOptions,\n type ResolvedNapplet,\n} from '@kehto/nip/5d';\nimport type { NostrEvent, NostrFilter } from '@napplet/core';\nimport type { AppletPointer, AppletSummary, RelayTiers } from '../types.js';\nimport { asFilters, type ApplesaucePool } from '../applesauce/relay-hooks.js';\nimport { addressOf } from '../catalog/entry.js';\n\n/**\n * Milliseconds a blob server gets before the next one is tried.\n *\n * @example\n * ```ts\n * await fetch(`${server}/${sha256}`, { signal: AbortSignal.timeout(BLOB_TIMEOUT_MS) }); // 20 s per server\n * ```\n */\nexport const BLOB_TIMEOUT_MS = 20_000;\n\n/** A pointer to something published: a built-in applet is never looked up. */\nexport type PublishedPointer = Exclude<AppletPointer, { kind: 'builtin' }>;\n\nfunction filterFor(pointer: PublishedPointer): NostrFilter {\n if (pointer.kind === 'event') return { ids: [pointer.id] };\n const filter: NostrFilter = { kinds: [pointer.eventKind], authors: [pointer.pubkey] };\n if (pointer.identifier !== '') filter['#d'] = [pointer.identifier];\n return filter;\n}\n\n/**\n * How long a manifest lookup waits, in milliseconds.\n *\n * `settleMs` runs from the first manifest, so a slower relay holding a newer\n * release can still answer. `patienceMs` runs from the first relay that\n * answers with nothing, so a slower relay that does hold the applet is not cut\n * off. `timeoutMs` bounds a round of asking when no relay answers at all; a\n * lookup is at most two rounds. `retryDelayMs` is the pause before a relay\n * that refused the connection is dialled once more.\n */\nexport interface ManifestTiming {\n readonly settleMs: number;\n readonly patienceMs: number;\n readonly timeoutMs: number;\n readonly retryDelayMs: number;\n}\n\n/**\n * The waits {@link fetchManifestEvent} uses unless told otherwise.\n *\n * @example\n * ```ts\n * MANIFEST_TIMING.timeoutMs; // 10000: the longest one round of asking can take\n * await fetchManifestEvent(pool, tiers, pointer, { patienceMs: 2_000 });\n * ```\n */\nexport const MANIFEST_TIMING: ManifestTiming = Object.freeze({ settleMs: 3_000, patienceMs: 8_000, timeoutMs: 10_000, retryDelayMs: 1_000 });\n\n\n/**\n * Relay URLs worth dialling, each once and in one spelling. Hints inside a\n * pointer are text a stranger wrote, so one that is not a websocket URL is\n * dropped instead of failing the lookup.\n */\nfunction dialable(urls: readonly string[]): string[] {\n const kept = new Map<string, string>();\n for (const url of urls) {\n if (!/^wss?:\\/\\//i.test(url) || !URL.canParse(url)) continue;\n const key = new URL(url).href;\n if (!kept.has(key)) kept.set(key, url);\n }\n return [...kept.values()];\n}\n\n/**\n * When the manifest request may stop before every relay has answered.\n *\n * applesauce's default stops three seconds after the first relay reports the\n * end of its stored events, found or not. A catalogue relay slower than a\n * general relay with nothing to say then loses the race and the applet reads\n * as missing. So the two cases get their own clocks: once a manifest is in,\n * the rest have `settleMs` to offer a newer one; once a relay has answered\n * with nothing, the rest have the longer `patienceMs` to do better. A relay\n * that accepts a connection and hangs up never answers either way, and\n * applesauce-relay 7 leaves it pending whatever `reconnect` or\n * `firstResponseTimeout` say, which is why the request also carries\n * `timeoutMs`.\n */\nfunction settleManifestRequest(timing: ManifestTiming): OperatorFunction<{ type: string }, boolean> {\n const after = (messages: Observable<{ type: string }>, type: string, waitMs: number): Observable<number> =>\n messages.pipe(filter((message) => message.type === type), take(1), switchMap(() => timer(waitMs)));\n return (messages) => merge(after(messages, 'EVENT', timing.settleMs), after(messages, 'EOSE', timing.patienceMs)).pipe(map(() => true));\n}\n\n/** What one round of asking produced: the newest manifest, and whether any relay answered at all. */\ninterface Asked {\n readonly newest?: NostrEvent;\n readonly answered: boolean;\n /** False when no relay of the round ever opened a connection. */\n readonly opened: boolean;\n}\n\ntype ConnectionState = { readonly connected$: { subscribe(next: (connected: boolean) => void): { unsubscribe(): void } } };\n\n/**\n * Watch whether any of these relays opens a connection while a round runs, as\n * kehto's reference host does. `connected$` replays the current state, so a\n * relay already connected counts. A pool that cannot say is taken to connect.\n */\nfunction watchOpened(pool: ApplesaucePool, relays: readonly string[]): { opened(): boolean; stop(): void } {\n const relayOf = (pool as { relay?: (url: string) => ConnectionState }).relay;\n if (typeof relayOf !== 'function') return { opened: () => true, stop: () => undefined };\n let opened = false;\n const watching = relays.map((url) => relayOf.call(pool, url).connected$.subscribe((connected) => void (opened ||= connected)));\n return { opened: () => opened, stop: () => watching.forEach((watch) => watch.unsubscribe()) };\n}\n\n/**\n * Ask the relays once, letting each refused connection be dialled one more\n * time after `retryDelayMs`. Busy public relays answer a websocket upgrade with\n * 502 or 503 for a moment and accept the next one. applesauce-relay 7.1\n * redials refused connections itself, three times with a growing pause by\n * default; one redial keeps a dead address from holding the lookup for most of\n * ten seconds. A relay that ran out its clock is not redialled: it already waited.\n */\nasync function askRelays(pool: ApplesaucePool, relays: string[], filter: NostrFilter, waits: ManifestTiming): Promise<Asked> {\n const watch = watchOpened(pool, relays);\n const request = pool.request(relays, asFilters([filter]), {\n complete: settleManifestRequest(waits),\n timeout: waits.timeoutMs,\n reconnect: { count: 1, delay: waits.retryDelayMs },\n });\n try {\n const events = await lastValueFrom(request.pipe(toArray()), { defaultValue: [] });\n const newest = events.reduce<NostrEvent | undefined>((best, event) => (best && best.created_at >= event.created_at ? best : event), undefined);\n // An empty answer from relays that never connected is not an answer; Firefox ends offline requests that way.\n return newest ? { newest, answered: true, opened: true } : { answered: watch.opened(), opened: watch.opened() };\n } catch {\n // Every relay failed, or none answered in time: the network could not say, which is not \"no such applet\".\n return { answered: false, opened: watch.opened() };\n } finally {\n watch.stop();\n }\n}\n\n/**\n * Fetch the manifest event a pointer names.\n *\n * The relays the address names and the `apps` tier are asked first. When they\n * do not produce the manifest, whether because they do not hold it or because\n * none of them answered, the `super` tier is asked before giving up: a\n * manifest is an ordinary event, authors publish it to general relays too, and\n * an address that opens elsewhere should not fail here because one catalogue\n * relay had a bad minute. For addresses, the newest event wins, since a named\n * applet is an addressable event that its author replaces on every release. A\n * relay that is down, silent or hangs up does not fail the lookup while\n * another one answers, a relay that refused the connection is dialled once\n * more, and hints that are not relay URLs are ignored.\n *\n * @param pool - The shared applesauce pool.\n * @param tiers - Relay tiers; `apps` is asked first, `super` as the fallback.\n * @param pointer - The decoded pointer.\n * @param timing - Overrides for {@link MANIFEST_TIMING}, applied to each round.\n * @returns The manifest event, unverified.\n * @throws `unavailable:manifest` when a relay answered and none had it, or\n * there was no relay to ask; `unavailable:unreachable` when every relay in every\n * round failed to open a connection; `unavailable:network` when no relay answered in time.\n * @example\n * ```ts\n * const event = await fetchManifestEvent(pool, tiers, decodePointer('naddr1…'));\n * ```\n */\nexport async function fetchManifestEvent(pool: ApplesaucePool, tiers: RelayTiers, pointer: PublishedPointer, timing: Partial<ManifestTiming> = {}): Promise<NostrEvent> {\n const config = tiers.get();\n const first = dialable([...pointer.relays, ...config.apps]);\n const rounds = [first, dialable([...first, ...config.super]).slice(first.length)].filter((relays) => relays.length > 0);\n const waits = { ...MANIFEST_TIMING, ...timing };\n const filter = filterFor(pointer);\n let answered = rounds.length === 0;\n let opened = rounds.length === 0;\n for (const relays of rounds) {\n const asked = await askRelays(pool, relays, filter, waits);\n if (asked.newest) return asked.newest;\n answered ||= asked.answered;\n opened ||= asked.opened;\n }\n // No relay opening a connection is usually the person's side: offline, a blocking network, or a browser out of sockets.\n if (answered) throw new Error('unavailable:manifest');\n throw new Error(opened ? 'unavailable:network' : 'unavailable:unreachable');\n}\n\n/**\n * Fetch an artifact blob by trying each server in turn with a 20-second budget.\n *\n * Bytes are returned unverified; `resolveNapplet` hashes them. Gateways are\n * accelerators, never identity.\n *\n * @param sha256 - The blob hash, lowercase hex.\n * @param servers - Server base URLs from the manifest.\n * @param fetchImpl - The fetch to use; the global one by default.\n * @returns The bytes the first responsive server returned.\n * @throws `unavailable:blob` when every server failed.\n * @example\n * ```ts\n * const bytes = await defaultFetchBlob(hash, ['https://blossom.example']);\n * ```\n */\nexport async function defaultFetchBlob(sha256: string, servers: readonly string[], fetchImpl: typeof fetch = fetch): Promise<Uint8Array> {\n for (const server of servers) {\n try {\n const response = await fetchImpl(`${server.replace(/\\/+$/, '')}/${sha256}`, { signal: AbortSignal.timeout(BLOB_TIMEOUT_MS) });\n if (response.ok) return new Uint8Array(await response.arrayBuffer());\n } catch {\n // The next server gets its turn; a dead gateway is not a verification failure.\n }\n }\n throw new Error('unavailable:blob');\n}\n\n/**\n * Reduce a verified napplet to what the shell shows before running it.\n *\n * @param resolved - The output of kehto's `resolveNapplet`.\n * @param address - The shareable address of the manifest event.\n * @returns The summary; `requires` and `optional` are advisory, never grants.\n * @example\n * ```ts\n * summarize(resolved, 'naddr1…').identity; // { dTag: 'chat', hash: '…' }\n * ```\n */\nexport function summarize(resolved: ResolvedNapplet, address: string): AppletSummary {\n const { manifest } = resolved;\n const summary: AppletSummary = {\n identity: { dTag: resolved.dTag, hash: resolved.aggregateHash },\n address,\n title: manifest.title ?? (resolved.dTag || 'Untitled applet'),\n description: manifest.description ?? '',\n publisher: manifest.pubkey,\n requires: Object.freeze([...manifest.requires]),\n optional: Object.freeze([...(manifest.optional ?? [])]),\n archetypes: Object.freeze([...(manifest.archetypeSlugs ?? manifest.archetypes.map((entry) => entry.slug))]),\n manifest,\n ...(manifest.icon ? { icon: manifest.icon } : {}),\n ...(manifest.source ? { source: manifest.source } : {}),\n };\n return summary;\n}\n\n/**\n * Open kehto's verified-artifact cache over Cache Storage when the page has\n * it, and nothing otherwise. Cached bytes are re-hashed on every read by\n * `resolveNapplet`, so the cache accelerates and never authenticates.\n *\n * @returns The cache, or undefined where Cache Storage is unavailable.\n * @example\n * ```ts\n * const cache = await openDefaultArtifactCache();\n * ```\n */\nexport async function openDefaultArtifactCache(): Promise<NappletArtifactCache | undefined> {\n if (typeof caches === 'undefined') return undefined;\n return openNappletArtifactCache({ cacheStorage: caches, requireStorageEstimate: false });\n}\n\n/** Inputs for {@link resolveApplet}. */\nexport interface ResolveAppletOptions {\n readonly event: NostrEvent;\n readonly fetchBlob: (sha256: string, servers: readonly string[]) => Promise<Uint8Array>;\n readonly cache?: NappletArtifactCache;\n /** Relay hints carried in the summary's address. */\n readonly relays?: readonly string[];\n}\n\n/** A verified applet: what to show and what to run. */\nexport interface ResolvedApplet {\n readonly summary: AppletSummary;\n /** The verified `index.html` text, before CSP and prelude insertion. */\n readonly indexHtml: string;\n}\n\nfunction reasonFor(error: NappletResolutionError): string {\n return error.code === 'blob-unavailable' ? 'unavailable:blob' : `invalid:${error.code}`;\n}\n\n/**\n * Verify a manifest event and its artifact through kehto's `resolveNapplet`.\n *\n * Resolution failures are rethrown with kernl's prefixed reasons: a missing\n * blob is `unavailable:blob`; a bad signature, manifest, hash or index is\n * `invalid:<code>` with kehto's code.\n *\n * @param options - Manifest event, blob fetcher and optional verified-artifact cache.\n * @returns The summary and verified index HTML.\n * @example\n * ```ts\n * const { summary, indexHtml } = await resolveApplet({ event, fetchBlob: defaultFetchBlob });\n * ```\n */\nexport async function resolveApplet(options: ResolveAppletOptions): Promise<ResolvedApplet> {\n const input: ResolveNappletOptions = { event: options.event, fetchBlob: options.fetchBlob };\n if (options.cache) input.cache = options.cache;\n try {\n const resolved = await resolveNapplet(input);\n return { summary: summarize(resolved, addressOf(options.event, options.relays)), indexHtml: resolved.indexHtml };\n } catch (error) {\n if (error instanceof NappletResolutionError) throw new Error(reasonFor(error));\n throw error;\n }\n}\n","import { naddrEncode, neventEncode } from 'applesauce-core/helpers';\nimport { NAPPLET_KIND_SNAPSHOT, parseNappletManifest, verifyManifestSignature, type NappletManifest } from '@kehto/nip/5d';\nimport type { NostrEvent } from '@napplet/core';\n\n/** One applet as the store lists it. Read from a signed manifest; its bytes are verified only when it is opened. */\nexport interface CatalogEntry {\n /** kehto's publisher- and kind-safe identity; the same id the intent catalogue uses. */\n readonly catalogId: string;\n /** A shareable address the launcher can decode: `naddr1…`, or `nevent1…` for a pinned version. */\n readonly address: string;\n readonly kind: number;\n readonly publisher: string;\n readonly title: string;\n readonly description: string;\n /** Lower-cased topics from the manifest's `t` tags. */\n readonly topics: readonly string[];\n readonly requires: readonly string[];\n /** Roles from `z` tags. */\n readonly archetypes: readonly string[];\n /** Accepted convention identities from `i` tags, such as `napplet:profile/open`. */\n readonly conventions: readonly string[];\n /** A display URL for the icon, from the manifest's first server. Never identity. */\n readonly iconUrl?: string;\n readonly publishedAt: number;\n}\n\nconst unique = (values: readonly string[]): readonly string[] => Object.freeze([...new Set(values)]);\n\nfunction topicsOf(event: NostrEvent): readonly string[] {\n return unique(event.tags.filter((tag) => tag[0] === 't' && typeof tag[1] === 'string' && tag[1].trim() !== '').map((tag) => (tag[1] as string).trim().toLowerCase()));\n}\n\nfunction iconUrlOf(manifest: NappletManifest): string | undefined {\n const server = manifest.servers[0];\n return manifest.icon && server ? `${server.replace(/\\/+$/, '')}/${manifest.icon.sha256}` : undefined;\n}\n\n/**\n * The address a person can paste back into the launcher for this manifest.\n *\n * @param event - A napplet manifest event.\n * @param relays - Where it was found; carried as hints, never as identity.\n * @returns `nevent1…` for a snapshot, `naddr1…` for a root or named applet.\n * @example\n * ```ts\n * addressOf(manifest, ['wss://relay.napplet.soy']); // 'naddr1…'\n * ```\n */\nexport function addressOf(event: NostrEvent, relays: readonly string[] = []): string {\n if (event.kind === NAPPLET_KIND_SNAPSHOT) return neventEncode({ id: event.id, author: event.pubkey, kind: event.kind, relays: [...relays] });\n const identifier = event.tags.find((tag) => tag[0] === 'd')?.[1] ?? '';\n return naddrEncode({ kind: event.kind, pubkey: event.pubkey, identifier, relays: [...relays] });\n}\n\n/**\n * Read a store entry from a manifest event.\n *\n * The signature is checked so a relay cannot list an applet under someone\n * else's name; the artifact is not fetched. Malformed manifests yield nothing.\n *\n * @param event - A candidate manifest event.\n * @param relays - Relay hints for the entry's address.\n * @returns The entry, or undefined when the event is not a valid signed manifest.\n * @example\n * ```ts\n * toCatalogEntry(event)?.topics; // ['game', 'puzzle']\n * ```\n */\nexport function toCatalogEntry(event: NostrEvent, relays: readonly string[] = []): CatalogEntry | undefined {\n let manifest: NappletManifest;\n try {\n if (!verifyManifestSignature(event)) return undefined;\n manifest = parseNappletManifest(event);\n } catch {\n return undefined;\n }\n const iconUrl = iconUrlOf(manifest);\n return Object.freeze({\n catalogId: manifest.catalogId,\n address: addressOf(event, relays),\n kind: event.kind,\n publisher: event.pubkey,\n title: manifest.title ?? (manifest.dTag || 'Untitled applet'),\n description: manifest.description ?? '',\n topics: topicsOf(event),\n requires: unique(manifest.requires),\n archetypes: unique(manifest.archetypeSlugs ?? manifest.archetypes.map((entry) => entry.slug)),\n conventions: unique(manifest.archetypes.map((entry) => entry.convention)),\n ...(iconUrl ? { iconUrl } : {}),\n publishedAt: event.created_at,\n });\n}\n\n/**\n * Keep the newest entry per catalogue id, newest first.\n *\n * Named and root applets are replaced on every release, so relays may hold\n * several versions; the store lists one.\n *\n * @param entries - Entries in any order, possibly repeated.\n * @returns One entry per applet.\n * @example\n * ```ts\n * newestEntries([older, newer]); // [newer]\n * ```\n */\nexport function newestEntries(entries: readonly CatalogEntry[]): readonly CatalogEntry[] {\n const newest = new Map<string, CatalogEntry>();\n for (const entry of entries) {\n const current = newest.get(entry.catalogId);\n if (!current || entry.publishedAt > current.publishedAt) newest.set(entry.catalogId, entry);\n }\n return Object.freeze([...newest.values()].sort((a, b) => b.publishedAt - a.publishedAt));\n}\n","import {\n assertNappletHasNoFrame,\n prepareNappletSrcdoc,\n renderNappletCspMeta,\n renderNappletNamespacePrelude,\n resolveShellEnvironment,\n type NappletCspDirectives,\n type NappletCspOptions,\n type NappletExperimentalOptions,\n type ShellAdapter,\n} from '@kehto/shell';\nimport { createAppletCsp, renderInsertionLockScript, type GuardProfile } from '@kernlize/guard';\nimport { renderRandomUuidFallbackScript } from '../crypto/install.js';\nimport type { AppletSummary, MountPlan } from '../types.js';\n\n/** Inputs for {@link planMount}. */\nexport interface PlanMountOptions {\n readonly summary: AppletSummary;\n /** Verified `index.html` text from {@link resolveApplet}. */\n readonly indexHtml: string;\n /** The live shell wiring; decides which domains exist at all. */\n readonly adapter: ShellAdapter;\n readonly guardProfile: GuardProfile;\n readonly windowId: string;\n}\n\n/**\n * Replace the first occurrence of `find` in `text`, refusing when it is absent.\n *\n * @param text - The text to edit.\n * @param find - The exact substring to replace.\n * @param replacement - What takes its place.\n * @returns The edited text.\n * @throws `Error('unavailable:frame-lock')` when `find` does not occur.\n * @example\n * ```ts\n * spliceOnce('a<b>c', '<b>', '<b><i>'); // 'a<b><i>c'\n * ```\n */\nexport function spliceOnce(text: string, find: string, replacement: string): string {\n const at = text.indexOf(find);\n if (at === -1) throw new Error('unavailable:frame-lock');\n return `${text.slice(0, at)}${replacement}${text.slice(at + find.length)}`;\n}\n\n/** kehto's nested-context lock: Trusted Types directives in the CSP, the policy and factory pins in the prelude. */\nconst NESTED_CONTEXT_LOCK: NappletExperimentalOptions = Object.freeze({ nestedContextLock: true });\n\n/**\n * Refuse verified markup that declares a nested frame, with kernl's stable\n * reason in place of kehto's message.\n *\n * @param html - Verified applet HTML.\n * @throws `Error('denied:nested-frame')` when kehto's scan finds a frame element.\n */\nfunction assertNoFrame(html: string): void {\n try {\n assertNappletHasNoFrame(html);\n } catch {\n throw new Error('denied:nested-frame');\n }\n}\n\n/**\n * Insert kernl's insertion lock (D-014) immediately after the CSP meta and\n * locked namespace prelude kehto put first in `<head>`, before any applet\n * script, followed by the `randomUUID` fallback (D-024) the prelude needs when\n * the shell is not a secure context. `@kehto/shell` has no hook for a second\n * prelude, so the pair is re-rendered and located in the srcdoc.\n */\nfunction addInsertionLock(srcdoc: string, csp: NappletCspOptions, domains: readonly string[]): string {\n const head = renderNappletCspMeta(csp, true) + renderNappletNamespacePrelude({ domains, experimental: NESTED_CONTEXT_LOCK });\n return spliceOnce(srcdoc, head, head + renderInsertionLockScript() + renderRandomUuidFallbackScript());\n}\n\n/**\n * Build everything `mountApplet` needs, without touching the DOM.\n *\n * The environment is kehto's `resolveShellEnvironment`, so it is the live\n * domains narrowed by the host's `capabilities.resolveEnvironment` (kernl's\n * grants). The CSP is the guard's zero-network profile, inserted first in\n * `<head>` by `prepareNappletSrcdoc` with kehto's nested-context lock enabled\n * (`experimental.nestedContextLock`): the policy gains kehto's Trusted Types\n * directives and the mandatory namespace prelude installs kehto's creation\n * lock. kernl's insertion lock follows the prelude. Markup that declares a\n * nested frame is refused by kehto's scan before any of that (D-014).\n * `missingRequired` lists what the applet asked for and will not get, so the\n * host can warn before mounting.\n *\n * @param options - Summary, verified HTML, adapter, guard profile and window id.\n * @returns A plan whose `srcdoc` is ready to assign.\n * @throws `Error('denied:nested-frame')` when the verified markup declares a frame element.\n * @throws `Error('unavailable:frame-lock')` when kehto's head cannot be found to place the insertion lock.\n * @example\n * ```ts\n * const plan = planMount({ summary, indexHtml, adapter, guardProfile: 'strict', windowId: 'w1' });\n * plan.sandbox; // 'allow-scripts'\n * ```\n */\nexport function planMount(options: PlanMountOptions): MountPlan {\n const { summary } = options;\n assertNoFrame(options.indexHtml);\n const environment = resolveShellEnvironment(options.adapter, { dTag: summary.identity.dTag, aggregateHash: summary.identity.hash });\n const domains = environment.capabilities.domains;\n const guardCsp = createAppletCsp(options.guardProfile);\n const csp: NappletCspOptions = { connectOrigins: guardCsp.connectOrigins, directives: guardCsp.directives as NappletCspDirectives };\n return {\n windowId: options.windowId,\n summary,\n srcdoc: addInsertionLock(prepareNappletSrcdoc(options.indexHtml, { domains, csp, experimental: NESTED_CONTEXT_LOCK }), csp, domains),\n sandbox: 'allow-scripts',\n environment,\n missingRequired: Object.freeze(summary.requires.filter((domain) => !domains.includes(domain))),\n };\n}\n","import { BehaviorSubject } from 'rxjs';\nimport { denyNappletControllerAccess, type OriginRegistry, type ShellBridge } from '@kehto/shell';\nimport type { WindowVisibility } from '@kernlize/guard';\nimport type { AppletHandle, AppletStatus, FrameLike, MountPlan } from '../types.js';\n\n/**\n * The Permissions-Policy `denyNappletControllerAccess` sets, for frames that cannot report their own.\n *\n * @example\n * ```ts\n * frame.setAttribute('allow', CONTROLLER_DENY_POLICY); // \"gamepad 'none'; hid 'none'; usb 'none'\"\n * ```\n */\nexport const CONTROLLER_DENY_POLICY = \"gamepad 'none'; hid 'none'; usb 'none'\";\n\n/** What the guard needs to know about a mounted window. */\nexport interface MountGuardHooks {\n setVisibility(windowId: string, visibility: WindowVisibility): void;\n /** Drop every queue and counter for the window. */\n forget(windowId: string): void;\n}\n\n/** Dependencies for {@link mountApplet}. */\nexport interface MountDeps {\n readonly bridge: Pick<ShellBridge, 'observeFrame' | 'revokeNapplet'>;\n readonly originRegistry: Pick<OriginRegistry, 'register' | 'setEnvironment' | 'unregister'>;\n readonly guard: MountGuardHooks;\n /** Called after the frame was removed because the bridge revoked the binding. */\n readonly onRevoked?: (windowId: string, reason: string) => void;\n}\n\n/** An {@link AppletHandle} with the entry point the bridge's revocation hook calls. */\nexport interface MountedApplet extends AppletHandle {\n /** Mark the applet revoked and remove its frame. Idempotent with `close`. */\n revoked(reason: string): void;\n}\n\nfunction hasGetAttribute(frame: FrameLike): frame is FrameLike & { getAttribute(name: string): string | null } {\n return typeof (frame as { getAttribute?: unknown }).getAttribute === 'function';\n}\n\nfunction harden(frame: FrameLike): void {\n // The attribute is replaced, not added to: a token the host left on the frame, such as allow-same-origin, would widen the sandbox (AGENTS.md, security posture).\n frame.setAttribute('sandbox', 'allow-scripts');\n if (hasGetAttribute(frame)) denyNappletControllerAccess(frame);\n else frame.setAttribute('allow', CONTROLLER_DENY_POLICY);\n}\n\n/**\n * Put a planned applet into a frame, in the NIP-5D order the shell depends on:\n * harden the frame, register its window with the verified identity, freeze its\n * environment, start watching for a second load, then assign `srcdoc`. The\n * status moves to `running` on the frame's first load.\n *\n * `close()` revokes the binding through the bridge, which closes the port and\n * destroys sessions and grants, then removes the frame. When the bridge revokes\n * the binding on its own, `revoked()` removes the frame and tells the host. The\n * frame is removed on every revocation reason; it is never reused.\n *\n * @param plan - The plan from {@link planMount}.\n * @param frame - An iframe, or any object with its shape, already in the DOM.\n * @param deps - Bridge, origin registry, guard hooks and the host's revocation callback.\n * @returns The running applet's handle.\n * @throws `invalid:frame-detached` when the frame has no `contentWindow`.\n * @example\n * ```ts\n * const handle = mountApplet(plan, iframe, { bridge, originRegistry, guard, onRevoked });\n * handle.setVisibility({ visible: true, focused: true });\n * handle.close();\n * ```\n */\nexport function mountApplet(plan: MountPlan, frame: FrameLike, deps: MountDeps): MountedApplet {\n const win = frame.contentWindow;\n if (!win) throw new Error('invalid:frame-detached');\n const { windowId } = plan;\n const status$ = new BehaviorSubject<AppletStatus>('mounting');\n let finished = false;\n\n harden(frame);\n deps.originRegistry.register(win, windowId, { dTag: plan.summary.identity.dTag, aggregateHash: plan.summary.identity.hash });\n deps.originRegistry.setEnvironment(win, plan.environment);\n const stopObserving = deps.bridge.observeFrame(frame, windowId);\n const onFirstLoad = (): void => {\n frame.removeEventListener('load', onFirstLoad);\n status$.next('running');\n };\n frame.addEventListener('load', onFirstLoad);\n frame.srcdoc = plan.srcdoc;\n\n const teardown = (status: AppletStatus): void => {\n finished = true;\n stopObserving();\n frame.removeEventListener('load', onFirstLoad);\n frame.remove();\n deps.guard.forget(windowId);\n status$.next(status);\n };\n\n return {\n windowId,\n summary: plan.summary,\n status$,\n get status() {\n return status$.value;\n },\n setVisibility: (visibility) => deps.guard.setVisibility(windowId, visibility),\n close() {\n if (finished) return;\n finished = true;\n deps.bridge.revokeNapplet(windowId, 'host');\n deps.originRegistry.unregister(windowId);\n teardown('closed');\n },\n revoked(reason) {\n if (finished) return;\n teardown('revoked');\n deps.onRevoked?.(windowId, reason);\n },\n };\n}\n","import { BehaviorSubject, type Observable } from 'rxjs';\nimport type { NappletMessageDecision } from '@kehto/shell';\nimport {\n classifyEnvelope,\n createFocusFirewall,\n createGuardConfig,\n createIngressGuard,\n createVisibilityGate,\n estimateEnvelopeSize,\n type AdmitOptions,\n type FocusFirewall,\n type GuardConfig,\n type GuardDisposition,\n type GuardEnvelope,\n type GuardEvent,\n type GuardProfile,\n type IngressGuard,\n type OpClass,\n type VisibilityGate,\n type WindowVisibility,\n} from '@kernlize/guard';\n\n/** The window a message came from, as the shell resolved it. Never taken from the message. */\nexport interface WindowResolution {\n readonly windowId: string;\n readonly napplet: string;\n}\n\n/** Options for {@link createGuardPipeline}. */\nexport interface GuardPipelineOptions {\n readonly config: GuardConfig;\n readonly now?: () => number;\n /** Receives every guard event from every layer. */\n readonly onEvent?: (event: GuardEvent) => void;\n /** Called once when a window crosses the quarantine threshold; kernl revokes it here, before the triggering envelope is dispatched. */\n readonly onQuarantine?: (windowId: string, napplet: string) => void;\n /** Visibility for a window the pipeline has not been told about yet. */\n readonly getVisibility?: (windowId: string) => WindowVisibility;\n /** Called when a window becomes visible; kernl releases the port envelopes kehto held for it here. */\n readonly onRelease?: (windowId: string) => void;\n}\n\n/** What the pipeline decided about a message. `unrouted` means no registered window sent it. */\nexport type PipelineDisposition = GuardDisposition | 'unrouted';\n\n/** A message held back until its window is visible or its budget refills. */\ninterface Pending {\n readonly event: MessageEvent;\n readonly napplet: string;\n readonly envelope: GuardEnvelope;\n readonly forward: (event: MessageEvent) => void;\n}\n\n/** The composed guard the shell puts in front of kehto's bridge. */\nexport interface GuardPipeline {\n readonly config: GuardConfig;\n readonly profile$: Observable<GuardProfile>;\n /** Rebuild every layer for a profile. Held messages are dropped; counters restart. */\n setProfile(profile: GuardProfile): void;\n /**\n * Admit, hold or drop one window-level message. Messages from unregistered\n * windows are forwarded so the bridge can report them as unrouted.\n */\n handleWindowMessage(event: MessageEvent, resolveWindow: (event: MessageEvent) => WindowResolution | null, forward: (event: MessageEvent) => void): PipelineDisposition;\n /**\n * Decide one envelope that arrived over a bound port, for kehto's\n * `filterNappletMessage`. `defer` holds every non-control envelope from a\n * window that is not visible (reason `hidden:<class>`) until it is visible\n * again, up to `deferQueue` envelopes. `drop` discards an envelope over its\n * size cap, a burst above the per-second rate, a request over the\n * focus-aware firewall's budget, a hidden window's envelope past the defer\n * queue, and the envelope that triggers a quarantine. Control envelopes are\n * dispatched unless the window is quarantined.\n */\n observe(windowId: string, napplet: string, message: unknown): NappletMessageDecision;\n setVisibility(windowId: string, visibility: WindowVisibility): void;\n getVisibility(windowId: string): WindowVisibility;\n /** Lift quarantine after the user chose to. */\n release(windowId: string): void;\n isQuarantined(windowId: string): boolean;\n /** Drop every queue and counter for a window. */\n forget(windowId: string): void;\n /** Forward what the budget and visibility now allow. */\n drainAll(windowId: string): void;\n}\n\ninterface Layers {\n ingress: IngressGuard;\n gate: VisibilityGate;\n firewall: FocusFirewall;\n}\n\nfunction toEnvelope(data: unknown): GuardEnvelope {\n const record = typeof data === 'object' && data !== null ? (data as Record<string, unknown>) : {};\n const event = typeof record.event === 'object' && record.event !== null ? (record.event as Record<string, unknown>) : {};\n const envelope: GuardEnvelope = {\n type: typeof record.type === 'string' ? record.type : 'unknown',\n size: estimateEnvelopeSize(data),\n };\n return typeof event.kind === 'number' ? { ...envelope, kind: event.kind } : envelope;\n}\n\n/** One envelope that arrived over a bound port, with the visibility the shell reported for its window. */\ninterface PortEnvelope {\n readonly windowId: string;\n readonly napplet: string;\n readonly envelope: GuardEnvelope;\n readonly visibility: WindowVisibility;\n}\n\n/** How the pipeline holds a hidden window's port envelope: counted against `deferQueue`, reported, and left with kehto. */\ntype HoldPort = (port: PortEnvelope, opClass: OpClass) => NappletMessageDecision;\n\n/**\n * What the pipeline answers for a port envelope once the ingress guard has\n * admitted it. Control envelopes are dispatched; a hidden window's other\n * envelopes are held; the rest go to the firewall.\n */\nfunction judgePort(port: PortEnvelope, admitted: GuardDisposition, firewall: FocusFirewall, hold: HoldPort): NappletMessageDecision {\n const { windowId, napplet, envelope, visibility } = port;\n if (admitted === 'quarantine') return 'drop';\n const opClass = classifyEnvelope(envelope);\n if (opClass === 'control') {\n if (admitted === 'pass') firewall.observe(windowId, napplet, envelope, visibility);\n return 'dispatch';\n }\n if (admitted !== 'pass') return 'drop';\n if (!visibility.visible) return hold(port, opClass);\n return firewall.observe(windowId, napplet, envelope, visibility).decision === 'pass' ? 'dispatch' : 'drop';\n}\n\n/**\n * Compose the guard: ingress flood control, then the visibility gate, then the\n * focus-aware firewall, then kehto's bridge.\n *\n * What is enforced where (D-020): kehto binds NAP traffic to a `MessagePort`\n * the bridge owns. Window-level messages, of which only `napplet.hello` is\n * legitimate, are held or dropped by `handleWindowMessage`. Port traffic\n * reaches `observe` through kehto's `filterNappletMessage`, whose answer\n * kehto follows: dispatch, hold until `releaseDeferred`, or drop. Hidden\n * windows' envelopes are held and `onRelease` is called when the window is\n * visible again. Quarantine revokes the window inside the filter, and kehto\n * discards what it held. The runtime firewall configured by\n * `applyRuntimeFirewallRules` adds the profile's per-class rates to every\n * envelope it dispatches, held ones included.\n *\n * @param options - Configuration, clock, event sink and quarantine callback.\n * @returns The pipeline.\n * @example\n * ```ts\n * const pipeline = createGuardPipeline({ config: createGuardConfig('strict'), onEvent: (e) => log.push(e) });\n * window.addEventListener('message', (event) => pipeline.handleWindowMessage(event, resolve, bridge.handleMessage));\n * ```\n */\nexport function createGuardPipeline(options: GuardPipelineOptions): GuardPipeline {\n let config = options.config;\n const profile$ = new BehaviorSubject<GuardProfile>(config.profile);\n const clock = options.now ?? Date.now;\n const known = new Map<string, WindowVisibility>();\n const heldByIngress = new Map<string, Pending[]>();\n const heldByGate = new Map<string, Pending[]>();\n const layerOptions = () => ({\n config,\n ...(options.now ? { now: options.now } : {}),\n ...(options.onEvent ? { onEvent: options.onEvent } : {}),\n });\n // The gate only asks for the applet while `defer` runs, which always follows `admit`.\n let deferring = '';\n const buildLayers = (): Layers => ({\n ingress: createIngressGuard(layerOptions()),\n gate: createVisibilityGate({ ...layerOptions(), nappletFor: () => deferring }),\n firewall: createFocusFirewall(layerOptions()),\n });\n let layers = buildLayers();\n\n function visibilityOf(windowId: string): WindowVisibility {\n if (!known.has(windowId) && options.getVisibility) {\n const visibility = options.getVisibility(windowId);\n known.set(windowId, visibility);\n layers.gate.setVisibility(windowId, visibility);\n }\n return layers.gate.getVisibility(windowId);\n }\n\n function push(queue: Map<string, Pending[]>, windowId: string, pending: Pending): void {\n const list = queue.get(windowId) ?? [];\n list.push(pending);\n queue.set(windowId, list);\n }\n\n function take(queue: Map<string, Pending[]>, windowId: string, count: number): Pending[] {\n const list = queue.get(windowId) ?? [];\n return list.splice(0, count);\n }\n\n function pastGate(windowId: string, pending: Pending): GuardDisposition {\n const opClass = classifyEnvelope(pending.envelope);\n if (layers.gate.shouldDefer(windowId, opClass)) {\n deferring = pending.napplet;\n if (!layers.gate.defer(windowId, pending.envelope)) return 'reject';\n push(heldByGate, windowId, pending);\n return 'defer';\n }\n return pastFirewall(windowId, pending);\n }\n\n function pastFirewall(windowId: string, pending: Pending): GuardDisposition {\n const result = layers.firewall.observe(windowId, pending.napplet, pending.envelope, visibilityOf(windowId));\n if (result.decision !== 'pass') return 'reject';\n pending.forward(pending.event);\n return 'pass';\n }\n\n function admit(windowId: string, napplet: string, envelope: GuardEnvelope, admitOptions?: AdmitOptions): GuardDisposition {\n const disposition = layers.ingress.admit(windowId, napplet, envelope, visibilityOf(windowId), admitOptions);\n if (disposition === 'quarantine') options.onQuarantine?.(windowId, napplet);\n return disposition;\n }\n\n function holdPort(port: PortEnvelope, opClass: OpClass): NappletMessageDecision {\n const { windowId, napplet } = port;\n deferring = napplet;\n if (!layers.gate.defer(windowId, port.envelope)) return 'drop';\n options.onEvent?.({ disposition: 'defer', windowId, napplet, opClass, reason: `hidden:${opClass}`, at: clock() });\n return 'defer';\n }\n\n function drainAll(windowId: string): void {\n const released = layers.ingress.drain(windowId).length;\n for (const pending of take(heldByIngress, windowId, released)) pastGate(windowId, pending);\n const visible = layers.gate.drain(windowId).length;\n for (const pending of take(heldByGate, windowId, visible)) pastFirewall(windowId, pending);\n }\n\n return {\n get config() {\n return config;\n },\n profile$,\n setProfile(profile) {\n config = createGuardConfig(profile);\n layers = buildLayers();\n heldByIngress.clear();\n heldByGate.clear();\n for (const [windowId, visibility] of known) layers.gate.setVisibility(windowId, visibility);\n profile$.next(profile);\n },\n handleWindowMessage(event, resolveWindow, forward) {\n const resolved = resolveWindow(event);\n if (!resolved) {\n forward(event);\n return 'unrouted';\n }\n const { windowId, napplet } = resolved;\n const pending: Pending = { event, napplet, envelope: toEnvelope(event.data), forward };\n const disposition = admit(windowId, napplet, pending.envelope);\n if (disposition === 'defer') push(heldByIngress, windowId, pending);\n return disposition === 'pass' ? pastGate(windowId, pending) : disposition;\n },\n observe(windowId, napplet, message) {\n const envelope = toEnvelope(message);\n const port: PortEnvelope = { windowId, napplet, envelope, visibility: visibilityOf(windowId) };\n return judgePort(port, admit(windowId, napplet, envelope, { hold: false }), layers.firewall, holdPort);\n },\n setVisibility(windowId, visibility) {\n known.set(windowId, visibility);\n layers.gate.setVisibility(windowId, visibility);\n if (!visibility.visible) return;\n drainAll(windowId);\n options.onRelease?.(windowId);\n },\n getVisibility: visibilityOf,\n release: (windowId) => layers.ingress.release(windowId),\n isQuarantined: (windowId) => layers.ingress.isQuarantined(windowId),\n forget(windowId) {\n layers.ingress.forget(windowId);\n layers.gate.forget(windowId);\n layers.firewall.forget(windowId);\n heldByIngress.delete(windowId);\n heldByGate.delete(windowId);\n known.delete(windowId);\n },\n drainAll,\n };\n}\n","import type { FirewallEvent } from '@kehto/runtime';\nimport { createFirewallState, type FirewallStateContainer, type NappletRules, type RateLimit } from '@kehto/rate-limit/legacy';\nimport { applyNappletRules, type GuardConfig, type GuardEvent, type OpClass } from '@kernlize/guard';\nimport type { StorageLike } from '../types.js';\n\n/*\n * Every call kernl makes into the runtime firewall's own configuration lives in\n * this module. Runtime 0.30 no longer builds a firewall: kernl constructs the\n * legacy one from `@kehto/rate-limit/legacy` and hands it over as\n * `legacyFirewall`, keeping the reference to configure it. Moving to\n * `permissions.rateLimiter` and `onRateLimit` is a change to this file (D-037).\n */\n\n/**\n * Where kernl stores the runtime firewall's configuration in the host storage.\n *\n * @example\n * ```ts\n * localStorage.getItem(RUNTIME_FIREWALL_STORAGE_KEY); // the serialised kehto firewall config\n * ```\n */\nexport const RUNTIME_FIREWALL_STORAGE_KEY = 'kernl:firewall:v1';\n\n/**\n * How the guard's operation classes appear inside kehto's runtime firewall.\n *\n * The runtime keys its observations by the sender capability a message needs\n * (`relay:write`, `resource:fetch`), while the guard classifies by what the\n * message does (`relay:publish`, `resource:bytes`). `null` means the class has\n * no runtime counterpart: deletions share `relay:write` with other publishes,\n * `control` envelopes need no capability, and `generic` becomes the per-applet\n * global rate.\n *\n * @example\n * ```ts\n * RUNTIME_OP_CLASSES['relay:publish']; // 'relay:write'\n * RUNTIME_OP_CLASSES.control; // null\n * ```\n */\nexport const RUNTIME_OP_CLASSES: Readonly<Record<OpClass, string | null>> = Object.freeze({\n 'relay:subscribe': 'relay:read',\n 'relay:publish': 'relay:write',\n 'relay:publish:delete': null,\n 'outbox:subscribe': 'outbox:read',\n 'outbox:publish': 'outbox:write',\n 'resource:bytes': 'resource:fetch',\n 'storage:write': 'state:write',\n 'dm:send': 'dm:write',\n 'intent:invoke': 'intent:write',\n control: null,\n generic: null,\n});\n\n/** One rate limit in the runtime's vocabulary. */\nexport interface RuntimeRateRule {\n readonly opClass: string;\n readonly limit: RateLimit;\n}\n\n/** The rules {@link applyRuntimeFirewallRules} installs for one applet. */\nexport interface RuntimeFirewallRules {\n readonly rates: readonly RuntimeRateRule[];\n readonly globalRate: RateLimit;\n}\n\n/**\n * Translate the guard profile's per-class rates for one applet into the\n * runtime firewall's `(napplet, opClass)` rate limits.\n *\n * @param config - Current guard configuration.\n * @param napplet - Applet identity (dTag).\n * @returns Runtime rate rules and the global fallback rate.\n * @example\n * ```ts\n * runtimeFirewallRules(createGuardConfig('strict'), 'chat').rates.find((r) => r.opClass === 'relay:write');\n * ```\n */\nexport function runtimeFirewallRules(config: GuardConfig, napplet: string): RuntimeFirewallRules {\n // applyNappletRules always registers the applet, so the entry exists.\n const rules = applyNappletRules(config, napplet).firewall.napplets[napplet] as NappletRules;\n const rates: RuntimeRateRule[] = [];\n for (const [opClass, limit] of Object.entries(rules.rateLimits)) {\n const runtimeClass = RUNTIME_OP_CLASSES[opClass as OpClass];\n if (runtimeClass) rates.push({ opClass: runtimeClass, limit });\n }\n return { rates, globalRate: rules.globalRate as RateLimit };\n}\n\n/** The runtime firewall's state, as far as kernl configures it. */\nexport type RuntimeFirewallState = Pick<FirewallStateContainer, 'setRateLimit' | 'setGlobalRate' | 'setUnfocusedMultiplier' | 'setBurstGuard' | 'persist'>;\n\n/**\n * Install the guard profile's rates for an applet in the runtime firewall.\n *\n * The runtime's firewall runs before every dispatch, including the envelopes\n * kernl held for a hidden window and released later, so the profile's limits\n * are pushed into it when a window mounts and again when the profile changes.\n * No policy is set: kehto's `allow` policy bypasses every rate, matcher and\n * burst check, and the user's choices to deny or block live in the grants\n * layer, not here.\n *\n * @param firewallState - The `legacyFirewall` from {@link createRuntimeFirewallHooks}.\n * @param config - Current guard configuration.\n * @param napplet - Applet identity (dTag).\n * @returns Nothing; the firewall state is mutated and persisted.\n * @example\n * ```ts\n * applyRuntimeFirewallRules(hooks.legacyFirewall, guardConfig, summary.identity.dTag);\n * ```\n */\nexport function applyRuntimeFirewallRules(firewallState: RuntimeFirewallState, config: GuardConfig, napplet: string): void {\n const rules = runtimeFirewallRules(config, napplet);\n for (const rule of rules.rates) firewallState.setRateLimit(napplet, rule.opClass, rule.limit);\n firewallState.setGlobalRate(napplet, rules.globalRate);\n firewallState.persist();\n}\n\n/**\n * Apply a profile's shell-wide limits to the runtime firewall: the unfocused\n * multiplier, which the runtime applies with the focus kernl reports through\n * `getFocusContext`, and the startup burst guard.\n *\n * @param firewallState - The `legacyFirewall` from {@link createRuntimeFirewallHooks}.\n * @param config - The guard configuration of the profile now in force.\n * @returns Nothing; the firewall state is mutated and persisted.\n * @example\n * ```ts\n * applyRuntimeFirewallProfile(hooks.legacyFirewall, createGuardConfig('balanced'));\n * hooks.legacyFirewall.getConfig().unfocusedMultiplier; // 0.5\n * ```\n */\nexport function applyRuntimeFirewallProfile(firewallState: RuntimeFirewallState, config: GuardConfig): void {\n firewallState.setUnfocusedMultiplier(config.firewall.unfocusedMultiplier);\n firewallState.setBurstGuard(config.firewall.burstGuard);\n firewallState.persist();\n}\n\nconst GUARD_OP_CLASSES: ReadonlyMap<string, OpClass> = new Map(\n Object.entries(RUNTIME_OP_CLASSES).flatMap(([opClass, runtimeClass]) => (runtimeClass ? [[runtimeClass, opClass as OpClass] as const] : [])),\n);\n\n/**\n * Turn a runtime firewall event into a guard event. The runtime's event\n * carries the applet's message; the guard event never does, so nothing the\n * applet sent reaches the guard log. Reasons follow the guard's vocabulary:\n * a rate is `rate:<class>`, the startup burst is `flood:startup`, anything\n * else is `runtime:<ruleId>`.\n *\n * @param event - What the runtime firewall reported.\n * @param at - When it happened.\n * @returns The guard event.\n * @example\n * ```ts\n * toGuardEvent({ windowId: 'w1', napplet: 'chat', opClass: 'state:write', decision: 'reject', action: 'block', ruleId: 'rate:opclass', reason: '…' }, 0).reason;\n * // 'rate:storage:write'\n * ```\n */\nexport function toGuardEvent(event: FirewallEvent, at: number): GuardEvent {\n const opClass = GUARD_OP_CLASSES.get(event.opClass) ?? 'generic';\n const reason = event.ruleId === 'burst' ? 'flood:startup' : event.ruleId.startsWith('rate:') ? `rate:${opClass}` : `runtime:${event.ruleId}`;\n const disposition = event.decision === 'pass' ? 'flag' : 'reject';\n return { disposition, windowId: event.windowId, napplet: event.napplet, opClass, reason, at };\n}\n\n/** The runtime firewall hooks kernl hands to `createShellAdapter`. */\nexport interface RuntimeFirewallHooks {\n /** The firewall the runtime evaluates; also what {@link applyRuntimeFirewallRules} configures. */\n readonly legacyFirewall: FirewallStateContainer;\n readonly onFirewallEvent: (event: FirewallEvent) => void;\n}\n\n/** Options for {@link createRuntimeFirewallHooks}. */\nexport interface RuntimeFirewallHooksOptions {\n /** The host storage; the config is kept under {@link RUNTIME_FIREWALL_STORAGE_KEY}. */\n readonly storage: StorageLike;\n /** Receives every runtime refusal and flag as a guard event. */\n readonly onEvent: (event: GuardEvent) => void;\n readonly now?: () => number;\n}\n\n/**\n * The runtime firewall, persisted in kernl's host storage, and its event\n * sink into the guard event stream. These report what the runtime itself\n * refused, which is the startup burst and anything over budget when held\n * envelopes are released; what kernl drops before the runtime sees it is\n * reported by kernl's own guard layers.\n *\n * @param options - Host storage, the guard event sink and a clock.\n * @returns `legacyFirewall` and `onFirewallEvent` for the `ShellAdapter`.\n * @example\n * ```ts\n * const hooks = createRuntimeFirewallHooks({ storage: localStorage, onEvent: (event) => log.push(event) });\n * const adapter: ShellAdapter = { ...rest, ...hooks };\n * applyRuntimeFirewallProfile(hooks.legacyFirewall, createGuardConfig('strict'));\n * ```\n */\nexport function createRuntimeFirewallHooks(options: RuntimeFirewallHooksOptions): RuntimeFirewallHooks {\n const now = options.now ?? Date.now;\n const legacyFirewall = createFirewallState({\n persist: (data) => options.storage.setItem(RUNTIME_FIREWALL_STORAGE_KEY, data),\n load: () => options.storage.getItem(RUNTIME_FIREWALL_STORAGE_KEY),\n });\n return {\n legacyFirewall,\n onFirewallEvent: (event) => options.onEvent(toGuardEvent(event, now())),\n };\n}\n","import type { Capability } from '@kehto/runtime';\n\n/**\n * Which kehto capabilities a NAP domain needs, following `resolveCapabilitiesNap`.\n * `shell` and `inc` map to nothing: the handshake needs no grant and `inc`\n * reuses the relay capabilities of the messages it carries.\n *\n * @example\n * ```ts\n * DOMAIN_CAPABILITIES.relay; // ['relay:read', 'relay:write']\n * DOMAIN_CAPABILITIES.shell; // []\n * ```\n */\nexport const DOMAIN_CAPABILITIES: Readonly<Record<string, readonly Capability[]>> = Object.freeze({\n shell: [],\n inc: [],\n relay: ['relay:read', 'relay:write'],\n identity: ['identity:read'],\n storage: ['state:read', 'state:write'],\n theme: ['theme:read'],\n keys: ['keys:bind', 'keys:forward'],\n media: ['media:control'],\n notify: ['notify:send', 'notify:channel'],\n config: ['config:read'],\n resource: ['resource:fetch'],\n cvm: ['cvm:call'],\n outbox: ['outbox:read', 'outbox:write'],\n upload: ['upload:write'],\n intent: ['intent:read', 'intent:write'],\n dm: ['dm:read', 'dm:write'],\n fs: ['fs:read', 'fs:write'],\n llm: ['llm:generate'],\n cache: ['cache:read', 'cache:write'],\n // kehto's ACL has no capability for direct connections; the service checks the grant itself (D-042).\n webrtc: [],\n});\n\n/**\n * Domains every applet gets without asking: the handshake, in-shell messaging,\n * the theme and scoped storage. No network, and not the identity: which\n * account is signed in is the user's to reveal, so an applet learns it only\n * after the user grants \"your account\" (SOUL opinion 2).\n *\n * @example\n * ```ts\n * BASELINE_DOMAINS.includes('identity'); // false: the account is the user's to reveal\n * capabilitiesForDomains(BASELINE_DOMAINS); // the capabilities granted without asking\n * ```\n */\nexport const BASELINE_DOMAINS: readonly string[] = Object.freeze(['shell', 'inc', 'theme', 'storage']);\n\n/**\n * Capabilities a domain needs. Unknown domains need none, which keeps the\n * grants layer honest about domains kehto adds later: they are advertised only\n * when the environment resolver allows them.\n *\n * @param domain - Bare NAP domain name.\n * @returns The capabilities, possibly empty.\n * @example\n * ```ts\n * capabilitiesForDomain('relay'); // ['relay:read', 'relay:write']\n * ```\n */\nexport function capabilitiesForDomain(domain: string): readonly Capability[] {\n return DOMAIN_CAPABILITIES[domain] ?? [];\n}\n\n/**\n * The union of capabilities a set of domains needs, deduplicated.\n *\n * @param domains - Bare NAP domain names.\n * @returns The capabilities in table order.\n * @example\n * ```ts\n * capabilitiesForDomains(['identity', 'storage']); // ['identity:read', 'state:read', 'state:write']\n * ```\n */\nexport function capabilitiesForDomains(domains: readonly string[]): readonly Capability[] {\n const wanted = new Set(domains);\n const result: Capability[] = [];\n for (const [domain, capabilities] of Object.entries(DOMAIN_CAPABILITIES)) {\n if (wanted.has(domain)) result.push(...capabilities);\n }\n return result;\n}\n","import { Subject } from 'rxjs';\nimport type { AclStateContainer, Capability } from '@kehto/runtime';\nimport type { CapabilityHooks } from '@kehto/shell';\nimport type { AppletIdentity, GrantRecord, Grants, StorageLike } from '../types.js';\nimport { createNamespacedStore } from '../persistence/store.js';\nimport { BASELINE_DOMAINS, capabilitiesForDomains } from './domain-capabilities.js';\n\nconst STORAGE_KEY = 'grants:v1';\n\ninterface StoredGrant {\n readonly dTag: string;\n readonly hash: string;\n readonly domains: readonly string[];\n readonly blocked: boolean;\n}\n\n/** Options for {@link createGrants}. */\nexport interface GrantsOptions {\n /** `bridge.runtime.aclState`; the live source of truth the runtime enforces. */\n readonly acl: AclStateContainer;\n readonly storage: StorageLike;\n /** Domains the shell can offer at all, from `buildShellCapabilities`. */\n readonly availableDomains: () => readonly string[];\n}\n\n/** The grants surface plus the hook the shell calls when an applet is about to run. */\nexport interface KernlGrants extends Grants {\n /** Write this applet's record into the runtime ACL before it runs; returns the record. */\n ensure(identity: AppletIdentity): GrantRecord;\n}\n\nfunction keyOf(identity: AppletIdentity): string {\n return `${identity.dTag}:${identity.hash}`;\n}\n\n/**\n * User-facing grants over kehto's ACL state.\n *\n * The runtime ACL is restrictive (`aclDefaultPolicy`, D-020): an applet with\n * no entry holds nothing. kernl grants the baseline domains plus what the user\n * allowed, and revokes whatever the applet's entry holds beyond that, which\n * covers a domain the user took back and an entry kept from an earlier\n * posture. The per-identity record is persisted at `kernl:grants:v1`; the ACL\n * itself is persisted by kehto. Blocking an applet blocks it in the ACL and empties its\n * environment through {@link createEnvironmentResolver}.\n *\n * @param options - ACL container, storage and the live domain list.\n * @returns The grants surface.\n * @example\n * ```ts\n * const grants = createGrants({ acl: bridge.runtime.aclState, storage, availableDomains });\n * grants.allowDomain(identity, 'relay');\n * grants.get(identity)?.capabilities; // includes 'relay:read' and 'relay:write'\n * ```\n */\nexport function createGrants(options: GrantsOptions): KernlGrants {\n const store = createNamespacedStore(options.storage, 'kernl');\n const records = new Map<string, StoredGrant>(Object.entries(store.getJson<Record<string, StoredGrant>>(STORAGE_KEY, {})));\n const changes$ = new Subject<GrantRecord>();\n\n const persist = (): void => store.setJson(STORAGE_KEY, Object.fromEntries(records));\n\n function stored(identity: AppletIdentity): StoredGrant {\n return records.get(keyOf(identity)) ?? { dTag: identity.dTag, hash: identity.hash, domains: [], blocked: false };\n }\n\n function record(entry: StoredGrant): GrantRecord {\n return {\n identity: { dTag: entry.dTag, hash: entry.hash },\n domains: Object.freeze([...entry.domains]),\n capabilities: capabilitiesForDomains([...BASELINE_DOMAINS, ...entry.domains]),\n blocked: entry.blocked,\n stateQuotaBytes: options.acl.getStateQuota('', entry.dTag, entry.hash),\n };\n }\n\n function syncAcl(entry: StoredGrant): void {\n const wanted = new Set<Capability>(capabilitiesForDomains([...BASELINE_DOMAINS, ...entry.domains]));\n const held = options.acl.getEntry('', entry.dTag, entry.hash)?.capabilities ?? [];\n for (const capability of held) if (!wanted.has(capability)) options.acl.revoke('', entry.dTag, entry.hash, capability);\n for (const capability of wanted) options.acl.grant('', entry.dTag, entry.hash, capability);\n if (entry.blocked) options.acl.block('', entry.dTag, entry.hash);\n else options.acl.unblock('', entry.dTag, entry.hash);\n options.acl.persist();\n }\n\n function commit(entry: StoredGrant): GrantRecord {\n records.set(`${entry.dTag}:${entry.hash}`, entry);\n persist();\n syncAcl(entry);\n const result = record(entry);\n changes$.next(result);\n return result;\n }\n\n function setDomains(identity: AppletIdentity, domains: readonly string[]): void {\n commit({ ...stored(identity), domains: [...domains] });\n }\n\n return {\n list: () => [...records.values()].map(record),\n get: (identity) => {\n const entry = records.get(keyOf(identity));\n return entry ? record(entry) : undefined;\n },\n ensure: (identity) => commit(stored(identity)),\n allowDomain(identity, domain) {\n if (!options.availableDomains().includes(domain)) throw new Error('invalid:domain');\n const current = stored(identity).domains;\n if (!BASELINE_DOMAINS.includes(domain) && !current.includes(domain)) setDomains(identity, [...current, domain]);\n },\n revokeDomain(identity, domain) {\n if (BASELINE_DOMAINS.includes(domain)) throw new Error('denied:baseline-domain');\n const current = stored(identity).domains;\n if (current.includes(domain)) setDomains(identity, current.filter((entry) => entry !== domain));\n },\n block: (identity) => void commit({ ...stored(identity), blocked: true }),\n unblock: (identity) => void commit({ ...stored(identity), blocked: false }),\n setStateQuota(identity, bytes) {\n options.acl.setStateQuota('', identity.dTag, identity.hash, bytes);\n commit(stored(identity));\n },\n availableDomains: () => options.availableDomains(),\n baselineDomains: () => BASELINE_DOMAINS,\n changes$,\n };\n}\n\n/**\n * The `capabilities.resolveEnvironment` hook for the `ShellAdapter`.\n *\n * Each applet sees the baseline domains plus the domains the user allowed,\n * intersected with what the shell offers live. kehto intersects again with\n * its own availability set, so this hook can only narrow. A blocked applet\n * sees only `shell`, enough to finish the handshake and nothing more.\n *\n * @param grants - The grants surface the hook reads.\n * @returns The hook, ready for `adapter.capabilities.resolveEnvironment`.\n * @example\n * ```ts\n * const adapter: ShellAdapter = { ..., capabilities: { resolveEnvironment: createEnvironmentResolver(grants) } };\n * ```\n */\nexport function createEnvironmentResolver(grants: Grants): NonNullable<CapabilityHooks['resolveEnvironment']> {\n return (identity, available) => {\n const record = grants.get({ dTag: identity.dTag, hash: identity.aggregateHash });\n const allowed = new Set(record?.blocked ? ['shell'] : [...grants.baselineDomains(), ...(record?.domains ?? [])]);\n return Object.freeze({\n domains: Object.freeze(available.domains.filter((domain) => allowed.has(domain))),\n services: Object.freeze(available.services.filter((service) => allowed.has(service))),\n });\n };\n}\n","import { getInboxes, getOutboxes, isReplaceable } from 'applesauce-core/helpers';\nimport type { NostrEvent } from '@napplet/core';\nimport type { AppletIdentity, ConsentLine, ConsentSummary } from '../types.js';\n\nconst PROFILE_FIELDS: readonly (readonly [key: string, label: string])[] = [\n ['name', 'Name'],\n ['display_name', 'Display name'],\n ['about', 'About'],\n ['picture', 'Picture'],\n ['banner', 'Banner'],\n ['nip05', 'Verified address'],\n ['lud16', 'Payment address'],\n ['website', 'Website'],\n];\n\nconst KIND_LABELS: Readonly<Record<number, string>> = {\n 1: 'post',\n 4: 'legacy private message',\n 6: 'repost',\n 7: 'reaction',\n 1059: 'sealed message',\n 1111: 'comment',\n 9735: 'payment receipt',\n 30023: 'article',\n};\n\n/** Content preview length for routine publishes. */\nconst PREVIEW_LENGTH = 140;\n/** Hex prefix shown for ids and keys. */\nconst PREFIX_LENGTH = 8;\n/** How many ids a line names before counting the rest. */\nconst NAMED_ITEMS = 3;\n\n/**\n * Shorten a hex id or key to a recognisable prefix.\n *\n * @param hex - A 64-hex id or public key.\n * @returns The first eight characters and an ellipsis.\n * @example\n * ```ts\n * abbreviate('3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d'); // '3bf0c63f…'\n * ```\n */\nexport function abbreviate(hex: string): string {\n return `${hex.slice(0, PREFIX_LENGTH)}…`;\n}\n\nfunction tagValues(event: NostrEvent | undefined, name: string): string[] {\n return (event?.tags ?? []).filter((tag) => tag[0] === name && typeof tag[1] === 'string').map((tag) => tag[1] as string);\n}\n\nconst HEX_KEY = /^[0-9a-f]{64}$/i;\nconst SERVER_ADDRESS = /^wss?:\\/\\//i;\nconst SERVER_TAGS = new Set(['r', 'relay', 'relays']);\nconst TYPE_TAGS = new Set(['k', 'kind']);\n\n/** A server address as the user knows it: no scheme, no trailing slash, no leading `relay.` or `nostr.` label while the rest still names a domain. */\nfunction serverName(address: string): string {\n return address.replace(SERVER_ADDRESS, '').replace(/\\/+$/, '').replace(/^(?:relay|nostr)\\.(?=[^/]*\\.)/i, '');\n}\n\nfunction recordNoun(kind: number | string): string {\n return KIND_LABELS[Number(kind)] ?? `record (type ${kind})`;\n}\n\nfunction coordinate(address: string): string {\n const [kind = '', pubkey = '', identifier = ''] = address.split(':');\n const named = identifier ? ` \"${identifier}\"` : '';\n return `${recordNoun(kind)}${named} by person ${abbreviate(pubkey)}`;\n}\n\nfunction entryLabel(name: string, value: string): string {\n if (name === 'p') return `person ${abbreviate(value)}`;\n if (name === 'e') return `item ${abbreviate(value)}`;\n if (name === 'a') return coordinate(value);\n if (name === 't') return `topic ${value}`;\n if (TYPE_TAGS.has(name)) return `type ${value}`;\n if (SERVER_TAGS.has(name) || SERVER_ADDRESS.test(value)) return `server ${serverName(value)}`;\n // A bare key is named for what it is; an unfamiliar tag name could be protocol vocabulary.\n if (HEX_KEY.test(value)) return `key ${abbreviate(value)}`;\n return `${name} ${value}`;\n}\n\nfunction listItems(event: NostrEvent | undefined): string[] {\n return (event?.tags ?? [])\n .filter((tag) => tag[0] !== 'd' && tag[0] !== 'title' && tag[0] !== 'description' && typeof tag[1] === 'string')\n .map((tag) => entryLabel(tag[0] as string, tag[1] as string));\n}\n\nfunction diff(before: readonly string[], after: readonly string[]): { added: string[]; removed: string[] } {\n const was = new Set(before);\n const now = new Set(after);\n return { added: after.filter((item) => !was.has(item)), removed: before.filter((item) => !now.has(item)) };\n}\n\nfunction describeItems(items: readonly string[], render: (item: string) => string): string {\n const named = items.slice(0, NAMED_ITEMS).map(render).join(', ');\n const rest = items.length - NAMED_ITEMS;\n return rest > 0 ? `${named} and ${rest} more` : named;\n}\n\nfunction changeLines(before: readonly string[], after: readonly string[], noun: string, render: (item: string) => string): ConsentLine[] {\n const { added, removed } = diff(before, after);\n const lines: ConsentLine[] = [];\n if (added.length > 0) lines.push({ label: `${noun} added`, after: `${added.length}: ${describeItems(added, render)}` });\n if (removed.length > 0) lines.push({ label: `${noun} removed`, before: `${removed.length}: ${describeItems(removed, render)}` });\n if (lines.length === 0) lines.push({ label: 'Change', after: 'No entries change' });\n return lines;\n}\n\nfunction parseProfile(event: NostrEvent | undefined): Record<string, unknown> {\n if (!event) return {};\n try {\n const parsed: unknown = JSON.parse(event.content);\n return typeof parsed === 'object' && parsed !== null ? (parsed as Record<string, unknown>) : {};\n } catch {\n return {};\n }\n}\n\nfunction text(value: unknown): string | undefined {\n return typeof value === 'string' && value !== '' ? value : undefined;\n}\n\nfunction profileLines(event: NostrEvent, before: NostrEvent | undefined): ConsentLine[] {\n const was = parseProfile(before);\n const now = parseProfile(event);\n const lines: ConsentLine[] = [];\n for (const [key, label] of PROFILE_FIELDS) {\n const previous = text(was[key]);\n const next = text(now[key]);\n if (previous === next) continue;\n const line: { label: string; before?: string; after?: string } = { label };\n if (previous !== undefined) line.before = previous;\n if (next !== undefined) line.after = next;\n lines.push(line);\n }\n if (lines.length === 0) lines.push({ label: 'Change', after: 'No profile fields change' });\n return lines;\n}\n\nconst MAILBOX_HELP: ConsentLine = { label: 'What this is', after: 'Your inbox is where people send things to you; your outbox is where your posts are kept and found.' };\n\n/**\n * A relay list (NIP-65) as the two lists a person knows: where they are reached\n * and where they publish. An unmarked entry is both and appears in each.\n */\nfunction mailboxLines(event: NostrEvent, before: NostrEvent | undefined): ConsentLine[] {\n const names = (urls: string[]): string[] => urls.map(serverName);\n const inbox = changeLines(names(before ? getInboxes(before) : []), names(getInboxes(event)), 'Inbox', (item) => item);\n const outbox = changeLines(names(before ? getOutboxes(before) : []), names(getOutboxes(event)), 'Outbox', (item) => item);\n const changed = [...inbox, ...outbox].filter((line) => line.label !== 'Change');\n return [MAILBOX_HELP, ...(changed.length > 0 ? changed : [{ label: 'Change', after: 'No entries change' }])];\n}\n\nfunction isListKind(kind: number): boolean {\n return (kind >= 10000 && kind <= 10099) || (kind >= 30000 && kind <= 30099);\n}\n\n/** Deletion request: erases the events and addresses it names. */\nconst DELETION = 5;\n/** Request to vanish: asks services to erase everything the account published. */\nconst VANISH = 62;\n/** The `relay` tag value a request to vanish uses to address every service. */\nconst ALL_SERVICES = 'ALL_RELAYS';\n\n/**\n * Whether {@link describeChange} rates a kind `destructive`: every replaceable\n * and addressable kind (signing one overwrites the version before it),\n * deletions, and requests to vanish.\n *\n * @param kind - The kind of the event about to be signed.\n * @returns True when signing it replaces or erases part of the account's public record.\n * @example\n * ```ts\n * isDestructiveKind(0); // true\n * isDestructiveKind(30311); // true\n * isDestructiveKind(1); // false\n * ```\n */\nexport function isDestructiveKind(kind: number): boolean {\n return isReplaceable(kind) || kind === DELETION || kind === VANISH;\n}\n\nfunction nameOf(event: NostrEvent): string | undefined {\n return tagValues(event, 'title')[0] ?? tagValues(event, 'd')[0];\n}\n\nfunction listTitle(event: NostrEvent): string {\n const name = nameOf(event);\n return name ? `Change the list \"${name}\"` : 'Change a list';\n}\n\nfunction replaceTitle(event: NostrEvent): string {\n const name = nameOf(event);\n // Every labelled kind is either not replaceable or falls in the list range, so only the type is known here.\n const label = `Replace one of your records (type ${event.kind})`;\n return name ? `${label} \"${name}\"` : label;\n}\n\nfunction recordLines(event: NostrEvent, before: NostrEvent | undefined): ConsentLine[] {\n const lines = changeLines(listItems(before), listItems(event), 'Entries', (item) => item);\n if (before !== undefined && before.content !== event.content) lines.push({ label: 'Content', after: 'Replaced' });\n return lines;\n}\n\nfunction deletion(event: NostrEvent, applet: AppletIdentity): ConsentSummary {\n const lines: ConsentLine[] = [\n ...tagValues(event, 'e').map((id) => ({ label: 'Delete', before: abbreviate(id) })),\n ...tagValues(event, 'a').map((address) => ({ label: 'Delete every version of', before: coordinate(address) })),\n ];\n // A deletion names posts only when its `k` tags say every target is one.\n const kinds = tagValues(event, 'k');\n const posts = tagValues(event, 'a').length === 0 && kinds.length > 0 && kinds.every((kind) => kind === '1');\n const noun = `${posts ? 'post' : 'item'}${lines.length === 1 ? '' : 's'}`;\n return destructive(event, applet, `Delete ${lines.length} ${noun}`, lines);\n}\n\nfunction vanish(event: NostrEvent, applet: AppletIdentity): ConsentSummary {\n const services = tagValues(event, 'relay');\n const everywhere = services.length === 0 || services.includes(ALL_SERVICES);\n const lines: ConsentLine[] = [{ label: 'Erase', before: 'Everything this account has published' }];\n lines.push({ label: 'Services asked', after: everywhere ? 'Every service' : describeItems(services, serverName) });\n return destructive(event, applet, 'Ask services to erase your account', lines);\n}\n\n/** The user's preferred applets for an archetype; an applet writing it could route other applets' requests to itself. */\nconst HANDLER_PREFERENCES = 31129;\n\n/** An applet named the way the user can recognise it: its name and publisher, or a pinned version's id. */\nfunction appletName(ref: string): string {\n const [, pubkey = '', name = ''] = ref.split(':');\n if (HEX_KEY.test(ref)) return `pinned applet ${abbreviate(ref)}`;\n return name ? `applet \"${name}\" by person ${abbreviate(pubkey)}` : `applet by person ${abbreviate(pubkey)}`;\n}\n\nfunction handlerEntries(event: NostrEvent | undefined): string[] {\n return (event?.tags ?? [])\n .filter((tag) => (tag[0] === 'a' || tag[0] === 'e' || tag[0] === 'i') && typeof tag[1] === 'string')\n .map((tag) => (tag[0] === 'i' ? `${appletName(tag[2] ?? '')} for \"${(tag[1] as string).replace(/^napplet:/, '')}\"` : appletName(tag[1] as string)));\n}\n\nfunction handlerPreferences(event: NostrEvent, before: NostrEvent | undefined, applet: AppletIdentity): ConsentSummary {\n const archetype = tagValues(event, 'd')[0] ?? 'some requests';\n const lines = changeLines(handlerEntries(before), handlerEntries(event), 'Applets', (entry) => entry);\n if (before !== undefined && before.content !== event.content) lines.push({ label: 'Private choices', after: 'Replaced' });\n return destructive(event, applet, `Change which applets open \"${archetype}\" for you`, lines);\n}\n\nfunction preview(content: string): string {\n const flat = content.replace(/\\s+/g, ' ').trim();\n return flat.length > PREVIEW_LENGTH ? `${flat.slice(0, PREVIEW_LENGTH)}…` : flat;\n}\n\nfunction destructive(event: NostrEvent, applet: AppletIdentity, title: string, lines: ConsentLine[]): ConsentSummary {\n return { title, severity: 'destructive', lines, applet, event };\n}\n\n/**\n * Describe a write the shell is asked to sign as what it changes.\n *\n * Profiles diff field by field; follow, connection and list changes count\n * what was added and removed and name the first few entries in plain words\n * (a person by key prefix, a server by its name); any other\n * replaceable or addressable record diffs its tags and says when its content\n * is replaced, without copying it; deletions list the events and addresses\n * that disappear; a request to vanish names the services asked; a change to\n * the user's preferred applets names the archetype and the applets added and\n * removed, because an applet that wrote it could route other applets'\n * requests to itself. Those kinds\n * are `destructive` because they replace or erase the account's public record. Everything else is `routine` and shows\n * a content preview. Nothing here is protocol vocabulary the user has to know,\n * and nothing secret is copied out of the event; the event itself rides along\n * unchanged for the record view.\n *\n * @param event - The event to be signed.\n * @param before - The current version of the replaceable event, when known.\n * @param applet - The applet asking.\n * @returns The summary the host renders.\n * @example\n * ```ts\n * describeChange(kind3Event, currentFollows, identity).lines[0];\n * // { label: 'Follows added', after: '1: 3bf0c63f…' }\n * ```\n */\nexport function describeChange(event: NostrEvent, before: NostrEvent | undefined, applet: AppletIdentity): ConsentSummary {\n switch (event.kind) {\n case 0:\n return destructive(event, applet, 'Update your profile', profileLines(event, before));\n case 3:\n return destructive(event, applet, 'Change who you follow', changeLines(tagValues(before, 'p'), tagValues(event, 'p'), 'Follows', abbreviate));\n case DELETION:\n return deletion(event, applet);\n case VANISH:\n return vanish(event, applet);\n case HANDLER_PREFERENCES:\n return handlerPreferences(event, before, applet);\n case 10002:\n return destructive(event, applet, 'Change your inbox and outbox', mailboxLines(event, before));\n default:\n if (isListKind(event.kind)) {\n return destructive(event, applet, listTitle(event), changeLines(listItems(before), listItems(event), 'Entries', (item) => item));\n }\n if (isReplaceable(event.kind)) return destructive(event, applet, replaceTitle(event), recordLines(event, before));\n return {\n title: `Publish a ${recordNoun(event.kind)}`,\n severity: 'routine',\n lines: [{ label: 'Content', after: preview(event.content) }],\n applet,\n event,\n };\n }\n}\n","import { catchError, EMPTY, lastValueFrom, takeUntil, timer, toArray } from 'rxjs';\nimport type { EventStore } from 'applesauce-core';\nimport { isAddressableKind, isReplaceable } from 'applesauce-core/helpers';\nimport type { AddressPointerLoader } from 'applesauce-loaders/loaders';\nimport type { ConsentRequest } from '@kehto/runtime';\nimport type { EventTemplate, NostrEvent } from '@napplet/core';\nimport type { AppletIdentity, ConsentLine, ConsentSummary, KernlHost } from '../types.js';\nimport { describeChange, isDestructiveKind } from './describe-change.js';\n\n/** Finds the current version of a replaceable event so the summary can show a diff; undefined when it cannot be found. */\nexport type LookupBefore = (kind: number, pubkey: string, identifier?: string) => Promise<NostrEvent | undefined>;\n\n/** Maps a window to the verified applet running in it. */\nexport type ResolveAppletIdentity = (windowId: string) => AppletIdentity | undefined;\n\n/**\n * How long a consent prompt waits for the network to return the current version, in milliseconds.\n *\n * @example\n * ```ts\n * const lookup = lookupReplaceable(eventStore, { loader, relays: () => tiers.super, timeoutMs: CURRENT_VERSION_TIMEOUT_MS / 2 });\n * ```\n */\nexport const CURRENT_VERSION_TIMEOUT_MS = 4000;\n\n/**\n * The line a destructive summary carries when the version it replaces could not be loaded.\n *\n * @example\n * ```ts\n * summary.lines[0] === UNKNOWN_CURRENT_VERSION; // true when the replaced version could not be loaded\n * UNKNOWN_CURRENT_VERSION.label; // 'Current version'\n * ```\n */\nexport const UNKNOWN_CURRENT_VERSION: ConsentLine = { label: 'Current version', after: 'could not be loaded; this replaces it entirely' };\n\n/** Options for {@link lookupReplaceable}. */\nexport interface LookupReplaceableOptions {\n /** Loads the current version from the network when the store has none. Without it the lookup reads the store only. */\n readonly loader?: AddressPointerLoader;\n /** The relays to ask, read each time a lookup runs. */\n readonly relays?: () => readonly string[];\n /** How long to wait for the loader; defaults to {@link CURRENT_VERSION_TIMEOUT_MS}. */\n readonly timeoutMs?: number;\n}\n\nfunction newest(events: readonly NostrEvent[]): NostrEvent | undefined {\n return events.reduce<NostrEvent | undefined>((best, event) => (!best || event.created_at > best.created_at ? event : best), undefined);\n}\n\n/**\n * A {@link LookupBefore} over the shell's event store and, on a miss, the\n * network.\n *\n * The store answers first. When it holds no version, the applesauce address\n * loader asks the given relays and the lookup waits at most `timeoutMs` for\n * an answer, then takes the newest version that arrived. A loader that fails\n * or stays silent yields undefined, which the consent summary reports as a\n * current version that could not be loaded.\n *\n * @param store - The event store that holds the current replaceable events.\n * @param options - Network loader, relays and timeout.\n * @returns A lookup for {@link createConsentHandler} and {@link createSigningConsent}.\n * @example\n * ```ts\n * const lookupBefore = lookupReplaceable(eventStore, { loader, relays: () => tiers.get().discovery });\n * createConsentHandler(host, lookupBefore, resolveApplet);\n * ```\n */\nexport function lookupReplaceable(store: Pick<EventStore, 'getReplaceable'>, options: LookupReplaceableOptions = {}): LookupBefore {\n const { loader } = options;\n return async (kind, pubkey, identifier) => {\n const cached = store.getReplaceable(kind, pubkey, identifier);\n if (cached || !loader) return cached;\n const pointer = { kind, pubkey, relays: [...(options.relays?.() ?? [])], ...(identifier === undefined ? {} : { identifier }) };\n const loaded = await lastValueFrom(\n loader(pointer).pipe(takeUntil(timer(options.timeoutMs ?? CURRENT_VERSION_TIMEOUT_MS)), catchError(() => EMPTY), toArray()),\n );\n return newest(loaded);\n };\n}\n\nfunction identifierOf(event: NostrEvent): string | undefined {\n if (!isAddressableKind(event.kind)) return undefined;\n const tag = event.tags.find((entry) => entry[0] === 'd');\n return tag?.[1] ?? '';\n}\n\n/**\n * Describe a write against the version it replaces. A replaceable or\n * addressable write whose current version cannot be found stays destructive\n * and says so first, rather than reading as a first version that removes\n * nothing.\n */\nasync function describeAgainstCurrent(event: NostrEvent, lookupBefore: LookupBefore, applet: AppletIdentity): Promise<ConsentSummary> {\n if (!isReplaceable(event.kind)) return describeChange(event, undefined, applet);\n const before = await lookupBefore(event.kind, event.pubkey, identifierOf(event));\n const summary = describeChange(event, before, applet);\n return before ? summary : { ...summary, lines: [UNKNOWN_CURRENT_VERSION, ...summary.lines] };\n}\n\n/**\n * Answer kehto's own consent requests.\n *\n * The kehto runtime kernl pins emits only `firewall-policy` requests, which\n * carry no event; kernl's guard decides firewall policy itself, so those are\n * refused without asking. Destructive writes are not asked for here: kehto\n * signs through `ShellAdapter.auth.getSigner`, and kernl gates that seam with\n * {@link createSigningConsent}. A request that does carry an event, from a\n * window the shell recognises, is still described and put to the user, so a\n * kehto release that adds such prompts is answered honestly; one from a\n * window the shell cannot name is refused.\n *\n * @param host - Supplies `presentConsent`.\n * @param lookupBefore - Finds the current replaceable event for the diff.\n * @param resolveApplet - Maps the requesting window to its applet identity.\n * @returns A handler for `bridge.registerConsentHandler`.\n * @example\n * ```ts\n * bridge.registerConsentHandler(createConsentHandler(host, lookupBefore, (windowId) => applets.get(windowId)?.summary.identity));\n * ```\n */\nexport function createConsentHandler(\n host: Pick<KernlHost, 'presentConsent'>,\n lookupBefore: LookupBefore,\n resolveApplet: ResolveAppletIdentity,\n): (request: ConsentRequest) => void {\n return (request) => {\n const applet = resolveApplet(request.windowId);\n const { event } = request;\n if (!event || !applet) {\n request.resolve(false);\n return;\n }\n void describeAgainstCurrent(event, lookupBefore, applet).then((summary) =>\n host.presentConsent({ summary, resolve: (allowed) => request.resolve(allowed) }),\n );\n };\n}\n\n/** The event fields the signing gate reads, as an applet supplied them. */\nexport type SigningTemplate = Readonly<Partial<EventTemplate>>;\n\n/**\n * Resolves when an applet's write may be signed and rejects with a stable\n * reason when it may not: `denied:consent` when the user refuses,\n * `denied:unknown-applet` for a destructive write from a window the shell did\n * not mount, `denied:signed-out` for a destructive write while nobody is\n * signed in, `invalid:event-kind` when the kind is not a number.\n */\nexport type SigningConsent = (windowId: string, template: SigningTemplate) => Promise<void>;\n\n/** What {@link createSigningConsent} needs from the shell. */\nexport interface SigningConsentOptions {\n readonly host: Pick<KernlHost, 'presentConsent'>;\n readonly lookupBefore: LookupBefore;\n readonly resolveApplet: ResolveAppletIdentity;\n /** The account that will sign, for the before lookup; undefined while nobody is signed in. */\n readonly pubkey: () => string | undefined;\n}\n\nfunction draftOf(template: SigningTemplate, kind: number, pubkey: string): NostrEvent {\n return {\n id: '',\n sig: '',\n pubkey,\n kind,\n created_at: template.created_at ?? 0,\n tags: Array.isArray(template.tags) ? template.tags : [],\n content: typeof template.content === 'string' ? template.content : '',\n };\n}\n\n/**\n * The consent gate kernl puts in front of every signature it makes for an\n * applet.\n *\n * Routine kinds pass without a prompt. A destructive kind (see\n * {@link isDestructiveKind}) is described against the account's current\n * version, from the event store or the network (see {@link lookupReplaceable}),\n * and put to the user through\n * `host.presentConsent`; the gate waits for the answer and nothing is signed\n * unless it is yes. The summary's `event` is the unsigned draft: its `id` and\n * `sig` are empty because signing has not happened yet.\n *\n * @param options - Host, before lookup, window-to-applet lookup and the signing pubkey.\n * @returns The gate for `createAuthHooks` and the outbox service.\n * @example\n * ```ts\n * const consent = createSigningConsent({ host, lookupBefore: lookupReplaceable(store), resolveApplet, pubkey: () => accounts.active?.pubkey });\n * await consent('applet-1', { kind: 0, content: '{\"name\":\"bob\"}', tags: [] }); // asks the user first\n * ```\n */\nexport function createSigningConsent(options: SigningConsentOptions): SigningConsent {\n return async (windowId, template) => {\n const { kind } = template;\n if (typeof kind !== 'number') throw new Error('invalid:event-kind');\n if (!isDestructiveKind(kind)) return;\n const applet = options.resolveApplet(windowId);\n if (!applet) throw new Error('denied:unknown-applet');\n const pubkey = options.pubkey();\n if (pubkey === undefined) throw new Error('denied:signed-out');\n const summary = await describeAgainstCurrent(draftOf(template, kind, pubkey), options.lookupBefore, applet);\n const allowed = await new Promise<boolean>((resolve) => options.host.presentConsent({ summary, resolve }));\n if (!allowed) throw new Error('denied:consent');\n };\n}\n","import {\n createGroupMessagesProvider,\n createLegacyMessagesProvider,\n createMessagingRegistry,\n createPrivateMessagesProvider,\n createRatchetMessagesProvider,\n type MessagingBackend,\n type MessagingRegistry,\n type MessagingRegistryOptions,\n type ProviderAvailability,\n type ProviderDeps,\n type SavedMessagingPreferences,\n} from '@kernlize/messaging';\nimport type { ISigner } from 'applesauce-signers';\nimport type { MessagingBackendFactories, StorageLike } from '../types.js';\nimport { createNamespacedStore } from '../persistence/store.js';\nimport { MESSAGING_UNAVAILABLE_REASONS, signerAvailability, type MessagingEncryption } from './availability.js';\n\nconst STORAGE_KEY = 'messaging:v1';\n\n/**\n * What is switched on for someone who has never chosen: the two providers that reach anyone with\n * an account, so a first message can be read and answered. The others publish something about\n * the account when they start, so they wait for the user to switch them on (D-016, D-018).\n */\nconst FIRST_RUN: SavedMessagingPreferences = Object.freeze({ enabled: Object.freeze(['private', 'legacy']) });\n\n/** Options for {@link createDefaultMessaging}. */\nexport interface DefaultMessagingOptions {\n readonly storage: StorageLike;\n /** Backend constructors; a provider without one stays unavailable. */\n readonly backends?: MessagingBackendFactories;\n /**\n * The active account's signer, read on every availability check. When given,\n * `private`, `ratchet` and `group` are available only while it has `nip44` and\n * `legacy` only while it has `nip04`, whichever backend is supplied for them.\n */\n readonly signer?: () => ISigner | undefined;\n /** Puts the reply question to the user; see `MessagingRegistryOptions.askReply`. */\n readonly askReply?: MessagingRegistryOptions['askReply'];\n}\n\nconst ENCRYPTION: Readonly<Record<keyof MessagingBackendFactories, MessagingEncryption>> = { private: 'nip44', legacy: 'nip04', ratchet: 'nip44', group: 'nip44' };\n\nfunction availabilityFor(id: keyof MessagingBackendFactories, options: DefaultMessagingOptions): () => ProviderAvailability {\n const factory = options.backends?.[id];\n const { signer } = options;\n if (factory && signer) return () => signerAvailability(signer(), ENCRYPTION[id]);\n if (factory) return () => ({ available: true });\n const reason = id === 'ratchet' || id === 'group' ? MESSAGING_UNAVAILABLE_REASONS.noRuntime : MESSAGING_UNAVAILABLE_REASONS.signInRequired;\n return () => ({ available: false, reason });\n}\n\nfunction depsFor(id: keyof MessagingBackendFactories, options: DefaultMessagingOptions): ProviderDeps {\n const available = availabilityFor(id, options);\n const factory = options.backends?.[id] as () => MessagingBackend;\n return {\n available,\n createBackend(): MessagingBackend {\n const availability = available();\n if (!availability.available) throw new Error(`unavailable:${availability.reason}`);\n return factory();\n },\n };\n}\n\n/**\n * The shell's messaging registry with kernl's four providers registered and\n * preferences persisted at `kernl:messaging:v1`.\n *\n * `createKernl` passes the account-signer backends for all four providers\n * and the active account's signer, so each follows the account:\n * `sign-in-required` while nobody is signed in, `signer-cannot-encrypt` while\n * the signer lacks the encryption the format needs. A provider given no\n * backend stays unavailable: `no-runtime` for `ratchet` and `group`, `sign-in-required`\n * for the others. The shell describes, it does not pretend.\n *\n * The providers start in the order private, legacy, ratchet, group, with\n * `private` and `legacy` switched on for someone who has never chosen; each\n * starts as soon as an account that can run it signs in. The user's own\n * choices, order, reply rule and per-person answers are saved and win.\n *\n * @param options - Storage, backend constructors, the active signer and the reply question.\n * @returns A `MessagingRegistry`.\n * @example\n * ```ts\n * const messaging = createDefaultMessaging({ storage: localStorage });\n * messaging.get('private')?.availability; // { available: false, reason: 'sign-in-required' }\n * messaging.get('ratchet')?.availability; // { available: false, reason: 'no-runtime' }\n * messaging.get('group')?.availability; // { available: false, reason: 'no-runtime' }\n * ```\n */\nexport function createDefaultMessaging(options: DefaultMessagingOptions): MessagingRegistry {\n const store = createNamespacedStore(options.storage, 'kernl');\n const registry = createMessagingRegistry({\n preferences: store.getJson<SavedMessagingPreferences | null>(STORAGE_KEY, null) ?? FIRST_RUN,\n ...(options.askReply ? { askReply: options.askReply } : {}),\n onChange: (next) => store.setJson(STORAGE_KEY, next),\n });\n registry.register(createPrivateMessagesProvider(depsFor('private', options)));\n registry.register(createLegacyMessagesProvider(depsFor('legacy', options)));\n registry.register(createRatchetMessagesProvider(depsFor('ratchet', options)));\n registry.register(createGroupMessagesProvider(depsFor('group', options)));\n return registry;\n}\n","import type { IAccount } from 'applesauce-accounts';\nimport type { ISigner } from 'applesauce-signers';\nimport type { ProviderAvailability } from '@kernlize/messaging';\nimport { isReadOnlyAccount } from '../applesauce/auth-hooks.js';\n\n/**\n * The encryption a messaging backend needs from the account signer.\n *\n * @example\n * ```ts\n * const method: MessagingEncryption = 'nip44';\n * ```\n */\nexport type MessagingEncryption = 'nip44' | 'nip04';\n\n/**\n * The reasons kernl gives for a provider that cannot run. Every provider\n * reports the first two, which follow the active account; `noRuntime` is\n * reported only by a `ratchet` or `group` provider a host registered without a backend.\n *\n * @example\n * ```ts\n * MESSAGING_UNAVAILABLE_REASONS.signInRequired; // 'sign-in-required'\n * Object.values(MESSAGING_UNAVAILABLE_REASONS); // ['sign-in-required', 'signer-cannot-encrypt', 'no-runtime']\n * ```\n */\nexport const MESSAGING_UNAVAILABLE_REASONS: Readonly<Record<'signInRequired' | 'signerCannotEncrypt' | 'noRuntime', string>> = Object.freeze({\n signInRequired: 'sign-in-required',\n signerCannotEncrypt: 'signer-cannot-encrypt',\n noRuntime: 'no-runtime',\n});\n\n/**\n * Whether a signer can carry messages that need `method`.\n *\n * @param signer - The active account's signer, or `undefined` while nobody is signed in.\n * @param method - The encryption the provider uses.\n * @returns Available, or unavailable with `sign-in-required` or `signer-cannot-encrypt`.\n * @example\n * ```ts\n * signerAvailability(undefined, 'nip44'); // { available: false, reason: 'sign-in-required' }\n * signerAvailability(new PrivateKeySigner(), 'nip44'); // { available: true }\n * ```\n */\nexport function signerAvailability(signer: ISigner | undefined, method: MessagingEncryption): ProviderAvailability {\n if (!signer) return { available: false, reason: MESSAGING_UNAVAILABLE_REASONS.signInRequired };\n return signer[method] ? { available: true } : { available: false, reason: MESSAGING_UNAVAILABLE_REASONS.signerCannotEncrypt };\n}\n\n/**\n * The signer messaging may use for an account. A read-only account is signed\n * in but can neither sign nor decrypt, so it is offered without its\n * encryption methods and reports `signer-cannot-encrypt`.\n *\n * @param account - The active account, if any.\n * @returns The account itself, a signer without encryption for a read-only account, or `undefined`.\n * @example\n * ```ts\n * const signer = () => messagingSigner(accounts.active);\n * signerAvailability(signer(), 'nip44');\n * ```\n */\nexport function messagingSigner(account: IAccount | undefined): ISigner | undefined {\n if (!account || !isReadOnlyAccount(account)) return account;\n return { getPublicKey: () => account.getPublicKey(), signEvent: (template) => account.signEvent(template) };\n}\n","import { kinds, verifyEvent, type NostrEvent } from 'applesauce-core/helpers';\nimport { lockGiftWrap, unlockGiftWrap } from 'applesauce-common/helpers/gift-wrap';\nimport { getConversationParticipants } from 'applesauce-common/helpers/messages';\nimport { sealRumor, toRumor } from 'applesauce-common/operations/gift-wrap';\nimport { PrivateKeySigner } from 'applesauce-signers';\nimport type { MessagingBackend } from '@kernlize/messaging';\nimport { createSignerBackend, type MessageFormat, type OpenedMessage, type SignerMessagingOptions } from './signer-backend.js';\n\n/** NIP-59 lets wraps carry a timestamp up to two days old so arrival times do not date the message. */\nconst WRAP_JITTER_SECONDS = 2 * 24 * 60 * 60;\n\n/**\n * Wrap a seal for one recipient under a key that exists for this wrap only.\n * The key is generated inside an applesauce `PrivateKeySigner` and goes out of\n * scope when the wrap is signed; it is never stored (SOUL opinion 1).\n */\nasync function wrapForRecipient(recipient: string, seal: NostrEvent, createdAt: number): Promise<NostrEvent> {\n const ephemeral = new PrivateKeySigner();\n const content = await ephemeral.nip44.encrypt(recipient, JSON.stringify(seal));\n const jitter = Math.floor(Math.random() * WRAP_JITTER_SECONDS);\n return ephemeral.signEvent({ kind: kinds.GiftWrap, created_at: createdAt - jitter, tags: [['p', recipient]], content });\n}\n\nasync function openWrap(event: NostrEvent, self: string, signer: Parameters<MessageFormat['open']>[2]): Promise<OpenedMessage | undefined> {\n const addressed = event.tags.some((tag) => tag[0] === 'p' && tag[1] === self);\n if (event.kind !== kinds.GiftWrap || !addressed || !verifyEvent(event)) return undefined;\n const rumor = await unlockGiftWrap(event, signer);\n lockGiftWrap(event);\n if (rumor.kind !== kinds.PrivateDirectMessage) return undefined;\n return { id: rumor.id, senderPubkey: rumor.pubkey, participants: getConversationParticipants(rumor), createdAt: rumor.created_at, content: rumor.content };\n}\n\n/**\n * The private message format: a kind 14 rumour sealed in a kind 13 event the\n * account signs, wrapped in a kind 1059 event signed by a one-time key.\n *\n * @example\n * ```ts\n * createSignerBackend(options, PRIVATE_MESSAGE_FORMAT);\n * ```\n */\nexport const PRIVATE_MESSAGE_FORMAT: MessageFormat = {\n implementation: 'nip17',\n encryption: 'nip44',\n filters: (self) => [{ kinds: [kinds.GiftWrap], '#p': [self] }],\n open: openWrap,\n async seal({ signer, self, others, content, createdAt, inboxRelays }) {\n // The rumour is built by hand: applesauce's text-content operation tags anyone mentioned in the text,\n // which would add them to the conversation on the reader's side.\n const rumor = await toRumor(signer)({ kind: kinds.PrivateDirectMessage, created_at: createdAt, content, tags: others.map((pubkey) => ['p', pubkey]) });\n const targets = [...others, self];\n const relays = await Promise.all(targets.map((target) => inboxRelays(target)));\n const outgoing = [];\n for (const [index, target] of targets.entries()) {\n const seal = await sealRumor(target, signer)(rumor);\n outgoing.push({ event: await wrapForRecipient(target, seal, createdAt), relays: relays[index] as string[] });\n }\n return { id: rumor.id, outgoing };\n },\n};\n\n/**\n * A `MessagingBackend` for private messages (NIP-17) over the active account's\n * signer.\n *\n * Sending builds a kind 14 rumour, seals it once per recipient and once for\n * the user in a kind 13 event signed by `signer()` and encrypted with its\n * `nip44`, and wraps each seal in a kind 1059 event signed by an ephemeral key\n * that lives only inside an applesauce `PrivateKeySigner` for that one wrap.\n * Each wrap goes to its recipient's kind 10050 inbox relays, or to the\n * `outbox` and `super` tiers when they publish none. Receiving subscribes to\n * kind 1059 events tagged with the user on the user's own inbox relays and\n * opens them with applesauce's gift-wrap helpers and the same signer; a wrap\n * that does not open, or holds anything but a kind 14 rumour, is ignored.\n *\n * Conversation ids are the sorted participant set, the user included, so both\n * sides of a conversation use the same id. Message ids are the rumour id, so\n * the copy addressed to the user is not filed twice.\n *\n * @param options - Store, pool, tiers, and the active account's signer and public key.\n * @returns A backend for the `private` provider; available while the signer has `nip44`.\n * @example\n * ```ts\n * const backend = createPrivateMessagesBackend({\n * store: kernl.eventStore,\n * pool: kernl.pool,\n * tiers: kernl.relays,\n * signer: () => kernl.accounts.active,\n * selfPubkey: () => kernl.accounts.active?.pubkey,\n * });\n * await backend.send({ recipients: [alice], content: 'hello' });\n * ```\n */\nexport function createPrivateMessagesBackend(options: SignerMessagingOptions): MessagingBackend {\n return createSignerBackend(options, PRIVATE_MESSAGE_FORMAT);\n}\n","import type { Observable } from 'rxjs';\nimport type { EventStore } from 'applesauce-core';\nimport { isHexKey, unixNow, type NostrEvent } from 'applesauce-core/helpers';\nimport { getConversationParticipants } from 'applesauce-common/helpers/messages';\nimport type { ISigner } from 'applesauce-signers';\nimport type { DmMessage, DmSendRequest, DmStatus, NostrFilter } from '@napplet/core';\nimport type { MessagingBackend } from '@kernlize/messaging';\nimport type { RelayTiers } from '../types.js';\nimport { subscribeWithEose, type ApplesaucePool, type EoseSubscription } from '../applesauce/relay-hooks.js';\nimport { createReplaceableLoader } from '../applesauce/identity-providers.js';\nimport { signerAvailability, type MessagingEncryption } from './availability.js';\nimport { conversationIdOf, createConversationStore } from './conversation-store.js';\nimport { createInboxRelays, type InboxRelays } from './inbox-relays.js';\n\n/**\n * What a signer-backed messaging backend needs from the shell. `signer` and\n * `selfPubkey` are read on every call, so one backend follows the active account.\n *\n * @example\n * ```ts\n * const options: SignerMessagingOptions = {\n * store: kernl.eventStore,\n * pool: kernl.pool,\n * tiers: kernl.relays,\n * signer: () => kernl.accounts.active,\n * selfPubkey: () => kernl.accounts.active?.pubkey,\n * };\n * ```\n */\nexport interface SignerMessagingOptions {\n /** The shell's event store; inbox relay lists are read from it. */\n readonly store: EventStore;\n readonly pool: ApplesaucePool;\n readonly tiers: RelayTiers;\n /** The active account's signer, read on every call. The only key holder the backend uses. */\n readonly signer: () => ISigner | undefined;\n /** The active account's public key, read on every call. */\n readonly selfPubkey: () => string | undefined;\n /** Clock in Unix seconds. Defaults to the wall clock. */\n readonly now?: () => number;\n /** Emits when the active account changes, so the inbox follows it without waiting for the next call. */\n readonly accountChanges?: Observable<unknown>;\n}\n\n/** A message read out of an event, before it is filed. */\nexport interface OpenedMessage {\n readonly id: string;\n readonly senderPubkey: string;\n /** Everyone the message names, sender included. */\n readonly participants: readonly string[];\n readonly createdAt: number;\n readonly content: string;\n}\n\n/** What a sealed message publishes: each event and the relays it goes to. */\nexport interface SealedMessage {\n readonly id: string;\n readonly outgoing: readonly { readonly event: NostrEvent; readonly relays: readonly string[] }[];\n}\n\n/** Everything a format needs to seal one message. */\nexport interface SealRequest {\n readonly signer: ISigner;\n readonly self: string;\n readonly others: readonly string[];\n readonly content: string;\n readonly createdAt: number;\n readonly inboxRelays: InboxRelays;\n}\n\n/** One message format: how to ask for, open and seal its events. */\nexport interface MessageFormat {\n readonly implementation: string;\n readonly encryption: MessagingEncryption;\n filters(self: string): NostrFilter[];\n /** Read an event addressed to or written by `self`; `undefined` for anything that does not open. */\n open(event: NostrEvent, self: string, signer: ISigner): Promise<OpenedMessage | undefined>;\n seal(request: SealRequest): Promise<SealedMessage>;\n}\n\ninterface Subscriber {\n readonly conversationId?: string;\n readonly onMessage: (message: DmMessage) => void;\n}\n\ninterface Inbox {\n readonly pubkey: string;\n ready: Promise<void>;\n handle?: EoseSubscription;\n}\n\ninterface Session {\n readonly signer: ISigner;\n readonly self: string;\n}\n\nconst CAPABILITIES = ['send', 'receive', 'subscribe', 'history'];\n\n/** The people a send goes to, other than `self`; refuses an unknown conversation, nobody, or a key that is not hex. */\nexport function recipientsOf(request: DmSendRequest, self: string): string[] {\n const named = request.conversationId === undefined ? request.recipients : getConversationParticipants(request.conversationId);\n if (request.conversationId !== undefined && !named.includes(self)) throw new Error('invalid:unknown-conversation');\n const others = [...new Set(named)].filter((pubkey) => pubkey !== self);\n if (others.length === 0) throw new Error('invalid:no-recipients');\n if (!others.every((pubkey) => isHexKey(pubkey))) throw new Error('invalid:recipient');\n return others;\n}\n\nasync function publishAll(pool: ApplesaucePool, sealed: SealedMessage): Promise<void> {\n for (const { event, relays } of sealed.outgoing) {\n const results = await pool.publish([...relays], event).catch(() => []);\n if (!results.some((result) => result.ok)) throw new Error('unavailable:offline');\n }\n}\n\n/**\n * A `MessagingBackend` for one message format, over the active account's\n * signer. The backend keeps one inbox subscription for the active account and\n * files what it can open into an in-memory store; when the account changes or\n * signs out, the subscription closes and the store is cleared, so one\n * account's messages are never shown to another.\n *\n * Reads wait for events that already arrived to be opened. A send files the\n * message as `sent` before publishing it and takes it back out if no relay\n * accepted it; the copy that later arrives from the user's own inbox carries\n * the same id and is not delivered twice.\n *\n * @param options - Store, pool, tiers, signer and clock.\n * @param format - How the format seals and opens its events.\n * @returns A backend for `createDefaultMessaging`.\n * @example\n * ```ts\n * const backend = createSignerBackend(options, privateMessageFormat);\n * await backend.send({ recipients: [alice], content: 'hi' });\n * ```\n */\nexport function createSignerBackend(options: SignerMessagingOptions, format: MessageFormat): MessagingBackend {\n const now = options.now ?? unixNow;\n const inboxRelays = createInboxRelays(options.store, createReplaceableLoader(options.store, options.pool, options.tiers), options.tiers);\n const store = createConversationStore();\n const subscribers = new Map<string, Subscriber>();\n const pending = new Set<Promise<void>>();\n let inbox: Inbox | undefined;\n let subscriptionCount = 0;\n\n const signerOf = (): ISigner | undefined => (options.selfPubkey() === undefined ? undefined : options.signer());\n const session = (): Session => {\n const signer = signerOf();\n const availability = signerAvailability(signer, format.encryption);\n if (!availability.available) throw new Error(`unavailable:${availability.reason}`);\n return { signer: signer as ISigner, self: options.selfPubkey() as string };\n };\n\n const file = (self: string, opened: OpenedMessage): DmMessage => {\n const participants = [...new Set([self, ...opened.participants])];\n const message: DmMessage = {\n id: opened.id,\n conversationId: conversationIdOf(participants),\n senderPubkey: opened.senderPubkey,\n createdAt: opened.createdAt,\n content: opened.content,\n status: opened.senderPubkey === self ? 'sent' : 'received',\n };\n if (store.owner !== self || !store.add(message, participants)) return message;\n for (const subscriber of subscribers.values()) {\n if (subscriber.conversationId === undefined || subscriber.conversationId === message.conversationId) subscriber.onMessage(message);\n }\n return message;\n };\n\n const ingest = (self: string, signer: ISigner, event: NostrEvent): void => {\n const opening = format.open(event, self, signer).then(\n (opened) => void (opened && file(self, opened)),\n () => undefined,\n );\n pending.add(opening);\n void opening.finally(() => pending.delete(opening));\n };\n\n const closeInbox = (): void => {\n inbox?.handle?.unsubscribe();\n inbox = undefined;\n store.reset();\n };\n\n const openInbox = (current: Session): Promise<void> => {\n store.reset(current.self);\n const entry: Inbox = { pubkey: current.self, ready: Promise.resolve() };\n inbox = entry;\n entry.ready = inboxRelays(current.self).then((relays) => {\n if (inbox !== entry) return;\n entry.handle = subscribeWithEose(options.pool, relays, format.filters(current.self), (item) => {\n if (item !== 'EOSE') ingest(current.self, current.signer, item);\n });\n });\n return entry.ready;\n };\n\n const sync = async (): Promise<void> => {\n if (!signerAvailability(signerOf(), format.encryption).available) closeInbox();\n else if (inbox?.pubkey !== options.selfPubkey()) {\n closeInbox();\n await openInbox(session());\n } else await inbox?.ready;\n await Promise.all(pending);\n };\n\n const changes = options.accountChanges?.subscribe(() => void sync());\n\n return {\n status(): DmStatus {\n const self = options.selfPubkey();\n return {\n available: signerAvailability(signerOf(), format.encryption).available,\n ...(self === undefined ? {} : { ownerPubkey: self }),\n implementations: [format.implementation],\n capabilities: CAPABILITIES,\n };\n },\n async conversations(query) {\n await sync();\n return store.conversations(query);\n },\n async messages(query) {\n await sync();\n return store.messages(query);\n },\n async send(request) {\n const current = session();\n const others = recipientsOf(request, current.self);\n await sync();\n const createdAt = now();\n const sealed = await format.seal({ ...current, others, content: request.content, createdAt, inboxRelays });\n const message = file(current.self, { id: sealed.id, senderPubkey: current.self, participants: others, createdAt, content: request.content });\n try {\n await publishAll(options.pool, sealed);\n } catch (error) {\n store.remove(message.conversationId, message.id);\n throw error;\n }\n return { ok: true, message };\n },\n async subscribe(request, onMessage) {\n await sync();\n subscriptionCount += 1;\n const subscriptionId = `${format.implementation}-${subscriptionCount}`;\n subscribers.set(subscriptionId, { ...(request.conversationId === undefined ? {} : { conversationId: request.conversationId }), onMessage });\n return { subscriptionId };\n },\n unsubscribe(subscriptionId) {\n return { ok: subscribers.delete(subscriptionId) };\n },\n close() {\n changes?.unsubscribe();\n subscribers.clear();\n closeInbox();\n },\n };\n}\n","import type { DmConversation, DmConversationPage, DmConversationQuery, DmMessage, DmMessagePage, DmMessageQuery } from '@napplet/core';\nimport { createConversationIdentifier } from 'applesauce-common/helpers/messages';\n\n/** Decrypted messages for one account, grouped by conversation. Lives in memory only. */\nexport interface ConversationStore {\n /** The account the stored messages belong to. */\n readonly owner: string | undefined;\n /** Forget every message and start over for `owner`. */\n reset(owner?: string): void;\n /** Store a message; `false` when one with the same id is already in its conversation. */\n add(message: DmMessage, participants: readonly string[]): boolean;\n remove(conversationId: string, id: string): void;\n conversations(query?: DmConversationQuery): DmConversationPage;\n messages(query: DmMessageQuery): DmMessagePage;\n}\n\ninterface Thread {\n readonly participants: readonly string[];\n readonly messages: DmMessage[];\n}\n\nconst DEFAULT_CONVERSATION_LIMIT = 50;\nconst DEFAULT_MESSAGE_LIMIT = 100;\n\n/**\n * The conversation id for a set of people: applesauce's identifier, the\n * sorted, deduplicated public keys joined by `:`. Both sides of a\n * conversation compute the same id because it includes the owner.\n *\n * @param participants - Every participant, the owner included.\n * @returns A stable id such as `\"<pubkey a>:<pubkey b>\"`.\n * @example\n * ```ts\n * conversationIdOf(['bb', 'aa', 'bb']); // 'aa:bb'\n * ```\n */\nexport function conversationIdOf(participants: readonly string[]): string {\n return createConversationIdentifier([...participants]);\n}\n\nfunction latest(thread: Thread): number {\n return Math.max(...thread.messages.map((message) => message.createdAt));\n}\n\nfunction page<T>(items: readonly T[], cursor: string | undefined, limit: number): { items: T[]; cursor?: string } {\n const offset = cursor === undefined ? 0 : Number.parseInt(cursor, 10) || 0;\n const slice = items.slice(offset, offset + limit);\n const end = offset + slice.length;\n return { items: slice, ...(end < items.length ? { cursor: String(end) } : {}) };\n}\n\n/**\n * An in-memory store of normalized messages for the account that owns it.\n * Messages are ordered by `createdAt`; a conversation's participants are the\n * people other than the owner, and it is a group when it has more than two\n * people. A conversation whose last message was removed is not listed.\n *\n * @returns An empty store with no owner.\n * @example\n * ```ts\n * const store = createConversationStore();\n * store.reset(me);\n * store.add(message, [me, alice]);\n * store.conversations().conversations[0]?.kind; // 'direct'\n * ```\n */\nexport function createConversationStore(): ConversationStore {\n const threads = new Map<string, Thread>();\n let owner: string | undefined;\n\n const summarize = (id: string, thread: Thread): DmConversation => {\n return {\n id,\n kind: thread.participants.length > 2 ? 'group' : 'direct',\n participants: thread.participants.filter((pubkey) => pubkey !== owner).map((pubkey) => ({ pubkey })),\n unread: thread.messages.filter((message) => message.status === 'received').length,\n updatedAt: latest(thread),\n };\n };\n\n return {\n get owner() {\n return owner;\n },\n reset(next) {\n owner = next;\n threads.clear();\n },\n add(message, participants) {\n const thread = threads.get(message.conversationId) ?? { participants: [...new Set(participants)].sort(), messages: [] };\n if (thread.messages.some((entry) => entry.id === message.id)) return false;\n thread.messages.push(message);\n thread.messages.sort((a, b) => a.createdAt - b.createdAt);\n threads.set(message.conversationId, thread);\n return true;\n },\n remove(conversationId, id) {\n const thread = threads.get(conversationId);\n thread?.messages.splice(thread.messages.findIndex((entry) => entry.id === id), 1);\n },\n conversations(query = {}) {\n const all = [...threads]\n .filter(([, thread]) => thread.messages.length > 0)\n .sort(([, a], [, b]) => latest(b) - latest(a))\n .map(([id, thread]) => summarize(id, thread));\n const result = page(all, query.cursor, query.limit ?? DEFAULT_CONVERSATION_LIMIT);\n return { conversations: result.items, ...(result.cursor === undefined ? {} : { cursor: result.cursor }) };\n },\n messages(query) {\n const all = threads.get(query.conversationId)?.messages ?? [];\n const result = page(all, query.cursor, query.limit ?? DEFAULT_MESSAGE_LIMIT);\n return { messages: result.items, ...(result.cursor === undefined ? {} : { cursor: result.cursor }) };\n },\n };\n}\n","import { lastValueFrom } from 'rxjs';\nimport type { EventStore } from 'applesauce-core';\nimport { kinds, mergeRelaySets, type NostrEvent } from 'applesauce-core/helpers';\nimport { getRelaysFromList } from 'applesauce-common/helpers/lists';\nimport type { AddressPointerLoader } from 'applesauce-loaders/loaders';\nimport type { RelayTiers } from '../types.js';\n\n/**\n * Resolves where a person reads their private messages and invitations.\n *\n * @example\n * ```ts\n * const inboxRelays: InboxRelays = async () => ['wss://inbox.example'];\n * ```\n */\nexport type InboxRelays = (pubkey: string) => Promise<string[]>;\n\n/**\n * Where to deliver to, or read from, a person's message inbox: the relays in\n * their kind 10050 list, loaded through the replaceable loader when the store\n * does not hold it, else the user's `outbox` and `super` tiers. The loader\n * completes empty when its relays fail, so a failed lookup also falls back.\n *\n * @param store - The shell's event store.\n * @param loader - The replaceable loader that fills the store on a miss.\n * @param tiers - Relay tiers; `discovery` is asked for the list, `outbox` and `super` are the fallback.\n * @returns A resolver from public key to relay URLs.\n * @example\n * ```ts\n * const inboxRelays = createInboxRelays(eventStore, loader, tiers);\n * await inboxRelays(pubkey); // ['wss://inbox.example'] or the outbox and super tiers\n * ```\n */\nexport function createInboxRelays(store: EventStore, loader: AddressPointerLoader, tiers: RelayTiers): InboxRelays {\n const load = async (pubkey: string): Promise<NostrEvent | undefined> => {\n const cached = store.getReplaceable(kinds.DirectMessageRelaysList, pubkey);\n if (cached) return cached;\n const pointer = { kind: kinds.DirectMessageRelaysList, pubkey, relays: [...tiers.get().discovery] };\n return lastValueFrom(loader(pointer), { defaultValue: undefined });\n };\n return async (pubkey) => {\n const list = await load(pubkey);\n const relays = list ? getRelaysFromList(list) : [];\n return relays.length > 0 ? relays : mergeRelaySets(tiers.get().outbox, tiers.get().super);\n };\n}\n","import { kinds, mergeRelaySets, verifyEvent, type NostrEvent } from 'applesauce-core/helpers';\nimport { isValidLegacyMessage, unlockLegacyMessage } from 'applesauce-common/helpers/legacy-messages';\nimport { getConversationParticipants } from 'applesauce-common/helpers/messages';\nimport { LegacyMessageFactory } from 'applesauce-common/factories/legacy-message';\nimport type { ISigner } from 'applesauce-signers';\nimport type { MessagingBackend } from '@kernlize/messaging';\nimport { createSignerBackend, type MessageFormat, type OpenedMessage, type SignerMessagingOptions } from './signer-backend.js';\n\nasync function openLegacy(event: NostrEvent, self: string, signer: ISigner): Promise<OpenedMessage | undefined> {\n if (!isValidLegacyMessage(event) || !verifyEvent(event)) return undefined;\n const participants = getConversationParticipants(event);\n if (!participants.includes(self)) return undefined;\n const content = await unlockLegacyMessage(event, self, signer);\n return { id: event.id, senderPubkey: event.pubkey, participants, createdAt: event.created_at, content };\n}\n\n/**\n * The legacy direct-message format: one kind 4 event encrypted with `nip04`,\n * whose author and recipient are public.\n *\n * @example\n * ```ts\n * createSignerBackend(options, LEGACY_MESSAGE_FORMAT);\n * ```\n */\nexport const LEGACY_MESSAGE_FORMAT: MessageFormat = {\n implementation: 'nip04',\n encryption: 'nip04',\n filters: (self) => [\n { kinds: [kinds.EncryptedDirectMessage], '#p': [self] },\n { kinds: [kinds.EncryptedDirectMessage], authors: [self] },\n ],\n open: openLegacy,\n async seal({ signer, self, others, content, createdAt, inboxRelays }) {\n if (others.length > 1) throw new Error('invalid:groups-unsupported');\n const recipient = others[0] as string;\n const event = await LegacyMessageFactory.create(recipient, content).created(createdAt).sign(signer);\n return { id: event.id, outgoing: [{ event, relays: mergeRelaySets(...(await Promise.all([inboxRelays(recipient), inboxRelays(self)]))) }] };\n },\n};\n\n/**\n * A `MessagingBackend` for the legacy direct-message format (NIP-04) over the\n * active account's signer.\n *\n * Sending encrypts the text to the one recipient with `signer().nip04`, signs\n * the kind 4 event with the account and publishes it to the recipient's inbox\n * relays and the user's own, so the user's other devices see it too. Receiving\n * subscribes to kind 4 events addressed to or written by the user and decrypts\n * them with the same signer. Conversation ids and message shapes match\n * {@link createPrivateMessagesBackend}; groups are refused with\n * `invalid:groups-unsupported` because the format has none.\n *\n * @param options - Store, pool, tiers, and the active account's signer and public key.\n * @returns A backend for the `legacy` provider; available while the signer has `nip04`.\n * @example\n * ```ts\n * const backend = createLegacyMessagesBackend({\n * store: kernl.eventStore,\n * pool: kernl.pool,\n * tiers: kernl.relays,\n * signer: () => kernl.accounts.active,\n * selfPubkey: () => kernl.accounts.active?.pubkey,\n * });\n * backend.subscribe({}, (message) => console.log(message.content));\n * ```\n */\nexport function createLegacyMessagesBackend(options: SignerMessagingOptions): MessagingBackend {\n return createSignerBackend(options, LEGACY_MESSAGE_FORMAT);\n}\n","import { verifyEvent, type NostrEvent } from 'applesauce-core/helpers';\nimport type { ISigner } from 'applesauce-signers';\nimport { NdrRuntime, type NdrRuntimeOptions, type Rumor } from 'nostr-double-ratchet';\nimport type { DmMessage, DmSendRequest, DmStatus, NostrFilter } from '@napplet/core';\nimport type { MessagingBackend } from '@kernlize/messaging';\nimport type { StorageLike } from '../types.js';\nimport { subscribeWithEose } from '../applesauce/relay-hooks.js';\nimport { signerAvailability } from './availability.js';\nimport { conversationIdOf, createConversationStore } from './conversation-store.js';\nimport { createSealedRatchetStorage } from './ratchet-storage.js';\nimport type { SignerMessagingOptions } from './signer-backend.js';\n\n/** The library's rumour kind for a chat message; typing notices, receipts and controls use others. */\nconst CHAT_MESSAGE_KIND = 14;\nconst CAPABILITIES = ['send', 'receive', 'subscribe', 'history', 'double-ratchet'];\n\n/**\n * What the ratchet backend needs: the signer backends' options plus the\n * storage the library's sealed state is kept in.\n *\n * @example\n * ```ts\n * const options: RatchetMessagingOptions = { ...signerOptions, storage: localStorage };\n * ```\n */\nexport interface RatchetMessagingOptions extends Omit<SignerMessagingOptions, 'store' | 'now'> {\n /** Where the library's device key and session state are kept, sealed to the account. */\n readonly storage: StorageLike;\n /**\n * How long the library waits for relays to return the account's device\n * list, as `{ fetchMs, fastMs }`. Defaults to the library's 10 s and 2 s.\n */\n readonly discoveryTimeouts?: { readonly fetchMs: number; readonly fastMs: number };\n}\n\ntype Transport = Pick<NdrRuntimeOptions, 'nostrSubscribe' | 'nostrPublish' | 'nostrSign'>;\n\ninterface Account {\n readonly self: string;\n readonly runtime: NdrRuntime;\n readonly ready: Promise<void>;\n readonly detach: () => void;\n /** Set when setup failed, so the next call starts over. */\n failed?: boolean;\n}\n\n/**\n * The library's relay seams over kernl's pool. Ratchet traffic is read from\n * and written to the user's `outbox` and `super` tiers, so both sides must\n * share a relay (D-016). Owner events the library leaves unsigned are signed\n * by the account signer; device and session events arrive already signed by\n * keys the library holds.\n */\nfunction transportFor(options: RatchetMessagingOptions, signer: ISigner): Transport {\n const relays = (): string[] => {\n const tiers = options.tiers.get();\n return [...new Set([...tiers.outbox, ...tiers.super])];\n };\n // The library leaves owner events with an empty `pubkey`; an account signer checks the hash it signs, so only the template goes to it.\n const sign = (event: NostrEvent): Promise<NostrEvent> =>\n typeof event.sig === 'string' ? Promise.resolve(event) : signer.signEvent({ kind: event.kind, created_at: event.created_at, tags: event.tags, content: event.content });\n type Verified = Awaited<ReturnType<NdrRuntimeOptions['nostrPublish']>>;\n return {\n nostrSign: async (event) => (await sign(event as NostrEvent)) as Verified,\n nostrSubscribe(filter, onEvent) {\n const handle = subscribeWithEose(options.pool, relays(), [filter as NostrFilter], (item) => {\n if (item !== 'EOSE' && verifyEvent(item)) onEvent(item as Verified);\n });\n return () => handle.unsubscribe();\n },\n async nostrPublish(event) {\n const signed = await sign(event as NostrEvent);\n const results = await options.pool.publish(relays(), signed).catch(() => []);\n if (!results.some((result) => result.ok)) throw new Error('unavailable:offline');\n return signed as Verified;\n },\n };\n}\n\nfunction recipientOf(request: DmSendRequest, self: string): string {\n const named = request.conversationId === undefined ? request.recipients : request.conversationId.split(':');\n if (request.conversationId !== undefined && !named.includes(self)) throw new Error('invalid:unknown-conversation');\n const others = [...new Set(named)].filter((pubkey) => pubkey !== self);\n if (others.length !== 1) throw new Error(others.length === 0 ? 'invalid:no-recipients' : 'invalid:groups-unsupported');\n return others[0] as string;\n}\n\n/**\n * A `MessagingBackend` for ratchet sessions (nostr-double-ratchet), over the\n * active account's signer.\n *\n * For each signed-in account the backend runs one `NdrRuntime`. The account\n * signer signs the owner's device list; the library generates and holds its\n * own device key and per-session ratchet keys, which never leave it except as\n * ciphertext sealed to the account by {@link createSealedRatchetStorage}.\n * Opening a runtime registers this browser as a device of the account and\n * publishes its invite, so a correspondent can start a session; sessions and\n * keys survive a reload, the conversation list does not (D-016).\n *\n * Only chat messages are filed: typing notices, receipts and controls are\n * dropped. Sessions are one to one, so a send names exactly one other person.\n * When the account changes or signs out the runtime closes and the\n * conversations are cleared.\n *\n * @param options - Pool, tiers, storage and the active account's signer and public key.\n * @returns A backend for the `ratchet` provider; available while the signer has `nip44`.\n * @example\n * ```ts\n * const backend = createRatchetMessagesBackend({\n * pool: kernl.pool,\n * tiers: kernl.relays,\n * storage: localStorage,\n * signer: () => kernl.accounts.active,\n * selfPubkey: () => kernl.accounts.active?.pubkey,\n * });\n * await backend.send({ recipients: [alice], content: 'hello' });\n * ```\n */\nexport function createRatchetMessagesBackend(options: RatchetMessagingOptions): MessagingBackend {\n const timeouts = options.discoveryTimeouts;\n const discovery = timeouts ? { appKeysFetchTimeoutMs: timeouts.fetchMs, appKeysFastTimeoutMs: timeouts.fastMs } : {};\n const store = createConversationStore();\n const subscribers = new Map<string, { conversationId?: string; onMessage(message: DmMessage): void }>();\n let account: Account | undefined;\n let subscriptionCount = 0;\n\n const signerOf = (): ISigner | undefined => (options.selfPubkey() === undefined ? undefined : options.signer());\n const usable = (): boolean => signerAvailability(signerOf(), 'nip44').available;\n\n const file = (self: string, message: DmMessage, participants: readonly string[]): void => {\n if (store.owner !== self || !store.add(message, participants)) return;\n for (const subscriber of subscribers.values()) {\n if (subscriber.conversationId === undefined || subscriber.conversationId === message.conversationId) subscriber.onMessage(message);\n }\n };\n\n const received = (self: string) => (rumor: Rumor, from: string): void => {\n if (rumor.kind !== CHAT_MESSAGE_KIND) return;\n const tagged = rumor.tags.filter((tag) => tag[0] === 'p').map((tag) => tag[1] as string);\n const participants = [...new Set([self, from, ...tagged])];\n const status = from === self ? 'sent' : 'received';\n file(self, { id: rumor.id, conversationId: conversationIdOf(participants), senderPubkey: from, createdAt: rumor.created_at, content: rumor.content, status }, participants);\n };\n\n const close = (): void => {\n account?.detach();\n account?.runtime.close();\n account = undefined;\n store.reset();\n };\n\n const open = (self: string, signer: ISigner): Account => {\n store.reset(self);\n const runtime = new NdrRuntime({\n ...transportFor(options, signer),\n storage: createSealedRatchetStorage({ storage: options.storage, signer, owner: self }),\n ...discovery,\n });\n const detach = runtime.onSessionEvent(received(self));\n const ready = (async () => {\n await runtime.initForOwner(self);\n await runtime.ensureCurrentDeviceRegistered(self);\n await runtime.republishInvite();\n })();\n return { self, runtime, ready, detach };\n };\n\n const sync = async (): Promise<Account | undefined> => {\n if (!usable()) close();\n else if (account?.self !== options.selfPubkey() || account?.failed) {\n close();\n account = open(options.selfPubkey() as string, signerOf() as ISigner);\n }\n const current = account;\n await current?.ready.catch(() => {\n current.failed = true;\n throw new Error('unavailable:offline');\n });\n return current;\n };\n\n const changes = options.accountChanges?.subscribe(() => void sync().catch(() => undefined));\n\n return {\n status(): DmStatus {\n const self = options.selfPubkey();\n return { available: usable(), ...(self === undefined ? {} : { ownerPubkey: self }), implementations: ['ndr'], capabilities: CAPABILITIES };\n },\n async conversations(query) {\n await sync();\n return store.conversations(query);\n },\n async messages(query) {\n await sync();\n return store.messages(query);\n },\n async send(request) {\n const availability = signerAvailability(signerOf(), 'nip44');\n if (!availability.available) throw new Error(`unavailable:${availability.reason}`);\n const self = options.selfPubkey() as string;\n const recipient = recipientOf(request, self);\n const current = (await sync()) as Account;\n const rumor = await current.runtime.sendMessage(recipient, request.content);\n const participants = [self, recipient];\n const message: DmMessage = { id: rumor.id, conversationId: conversationIdOf(participants), senderPubkey: self, createdAt: rumor.created_at, content: request.content, status: 'sent' };\n file(self, message, participants);\n return { ok: true, message };\n },\n async subscribe(request, onMessage) {\n await sync();\n subscriptionCount += 1;\n const subscriptionId = `ndr-${subscriptionCount}`;\n subscribers.set(subscriptionId, { ...(request.conversationId === undefined ? {} : { conversationId: request.conversationId }), onMessage });\n return { subscriptionId };\n },\n unsubscribe(subscriptionId) {\n return { ok: subscribers.delete(subscriptionId) };\n },\n close() {\n changes?.unsubscribe();\n subscribers.clear();\n close();\n },\n };\n}\n","import type { ISigner } from 'applesauce-signers';\nimport type { StorageAdapter } from 'nostr-double-ratchet';\nimport type { StorageLike } from '../types.js';\n\n/** NIP-44 encrypts at most 65535 bytes; a UTF-16 code unit takes at most three UTF-8 bytes, so 16384 units always fit. */\nconst CHUNK_UNITS = 16_384;\n\ninterface SlotIndex {\n next: number;\n slots: Record<string, number>;\n}\n\n/**\n * What {@link createSealedRatchetStorage} needs.\n *\n * @example\n * ```ts\n * const options: SealedRatchetStorageOptions = { storage: localStorage, signer: account, owner: account.pubkey };\n * ```\n */\nexport interface SealedRatchetStorageOptions {\n readonly storage: StorageLike;\n /** The account signer; every value is encrypted to `owner` with its `nip44`. */\n readonly signer: ISigner;\n readonly owner: string;\n}\n\nfunction chunks(text: string): string[] {\n const parts: string[] = [];\n for (let start = 0; start < text.length; start += CHUNK_UNITS) parts.push(text.slice(start, start + CHUNK_UNITS));\n return parts;\n}\n\n/**\n * The ratchet library's storage, sealed to the account. The library keeps its\n * device key and session state here; kernl writes each value only as\n * ciphertext the account signer encrypted to itself with `nip44`, under an\n * opaque slot number, and keeps the map from the library's key names (which\n * name correspondents) to slots in one more sealed entry. Nothing readable\n * reaches `storage`, so the key rule in `SOUL.md` opinion 1 holds for every\n * secret the library generates (D-016).\n *\n * Values are decrypted once and then served from memory, so an extension or\n * remote signer is asked once per value per page load. Writes are applied in\n * order.\n *\n * @param options - Backing storage, the account signer and its public key.\n * @returns A `StorageAdapter` for `NdrRuntime`.\n * @example\n * ```ts\n * const storage = createSealedRatchetStorage({ storage: localStorage, signer: account, owner: account.pubkey });\n * await storage.put('v1/note', { hello: 'world' });\n * await storage.get('v1/note'); // { hello: 'world' }\n * ```\n */\nexport function createSealedRatchetStorage(options: SealedRatchetStorageOptions): StorageAdapter {\n const { storage, owner } = options;\n const nip44 = options.signer.nip44 as NonNullable<ISigner['nip44']>;\n const prefix = `kernl:ratchet:v1:${owner}:`;\n const values = new Map<string, unknown>();\n let writes: Promise<void> = Promise.resolve();\n\n const seal = async (value: unknown): Promise<string> => {\n const parts = await Promise.all(chunks(JSON.stringify(value)).map((part) => nip44.encrypt(owner, part)));\n return JSON.stringify(parts);\n };\n const open = async <T>(raw: string): Promise<T> => {\n const parts = await Promise.all((JSON.parse(raw) as string[]).map((part) => nip44.decrypt(owner, part)));\n return JSON.parse(parts.join('')) as T;\n };\n\n const readIndex = async (): Promise<SlotIndex> => {\n const raw = storage.getItem(`${prefix}index`);\n return raw === null ? { next: 0, slots: {} } : open<SlotIndex>(raw);\n };\n const loading = readIndex();\n const write = (task: (index: SlotIndex) => Promise<void>): Promise<void> => {\n writes = writes.then(async () => task(await loading));\n return writes;\n };\n const saveIndex = async (index: SlotIndex): Promise<void> => storage.setItem(`${prefix}index`, await seal(index));\n\n return {\n async get<T = unknown>(key: string): Promise<T | undefined> {\n if (values.has(key)) return values.get(key) as T;\n const slot = (await loading).slots[key];\n const raw = slot === undefined ? null : storage.getItem(`${prefix}${slot}`);\n if (raw === null) return undefined;\n const value = await open<T>(raw);\n if (!values.has(key)) values.set(key, value);\n return values.get(key) as T;\n },\n put<T = unknown>(key: string, value: T): Promise<void> {\n values.set(key, value);\n return write(async (index) => {\n const known = index.slots[key];\n const slot = known ?? index.next;\n storage.setItem(`${prefix}${slot}`, await seal(value));\n if (known !== undefined) return;\n index.slots[key] = slot;\n index.next = slot + 1;\n await saveIndex(index);\n });\n },\n del(key: string): Promise<void> {\n values.delete(key);\n return write(async (index) => {\n const slot = index.slots[key];\n if (slot === undefined) return;\n storage.removeItem(`${prefix}${slot}`);\n delete index.slots[key];\n await saveIndex(index);\n });\n },\n async list(match = ''): Promise<string[]> {\n await writes;\n return Object.keys((await loading).slots).filter((key) => key.startsWith(match));\n },\n };\n}\n","import { unixNow } from 'applesauce-core/helpers';\nimport type { ISigner } from 'applesauce-signers';\nimport { createApplicationMessageIntent, createChatRumor } from '@internet-privacy/marmot-ts';\nimport type { DmMessage, DmStatus } from '@napplet/core';\nimport type { MessagingBackend } from '@kernlize/messaging';\nimport type { StorageLike } from '../types.js';\nimport { createReplaceableLoader } from '../applesauce/identity-providers.js';\nimport { signerAvailability } from './availability.js';\nimport { createConversationStore } from './conversation-store.js';\nimport { createGroupNetwork } from './group-network.js';\nimport { groupIdOf, membersOf, openGroupSession, type GroupSession, type GroupSessionContext } from './group-session.js';\nimport { createInboxRelays } from './inbox-relays.js';\nimport { recipientsOf, type SignerMessagingOptions } from './signer-backend.js';\n\nconst CAPABILITIES = ['send', 'receive', 'subscribe', 'history'];\n\n/**\n * What the group backend needs: the signer-backend options plus storage for\n * the group library's state, which is sealed to the account before it is\n * written.\n *\n * @example\n * ```ts\n * const options: GroupMessagingOptions = { ...signerOptions, storage: localStorage };\n * ```\n */\nexport interface GroupMessagingOptions extends SignerMessagingOptions {\n readonly storage: StorageLike;\n}\n\ninterface Subscriber {\n readonly conversationId?: string;\n readonly onMessage: (message: DmMessage) => void;\n}\n\n/**\n * A `MessagingBackend` for group sessions (Marmot, MLS over Nostr) over the\n * active account's signer, built on `@internet-privacy/marmot-ts`.\n *\n * The account signer proves who each member is and opens invitations; the\n * group library holds the group secrets, which move on with every commit, and\n * kernl seals everything the library stores to the account with `nip44`\n * (D-018). When an account first uses the backend it publishes a key package\n * (kind 30443) to its inbox relays and `outbox` tier, so others can start a\n * group with it, and publishes a fresh one after each invitation uses it up.\n *\n * A send to people goes to the group with exactly those members, else to a\n * new one that invites each of them by their key package; a recipient with\n * none is refused with `unavailable:recipient-not-ready`. Group events (kind\n * 445) go to the `outbox` and `super` tiers. Invitations arrive as gift wraps\n * on the user's inbox relays and are joined as they open. When the account\n * changes or signs out, the session closes and its messages are forgotten.\n *\n * Conversation ids are the group id in hex. A device is one member, so a\n * second device of the same account sees only groups it was invited to.\n *\n * @param options - Store, pool, tiers, storage, and the active account's signer and public key.\n * @returns A backend for the `group` provider; available while the signer has `nip44`.\n * @example\n * ```ts\n * const backend = createGroupMessagesBackend({\n * store: kernl.eventStore,\n * pool: kernl.pool,\n * tiers: kernl.relays,\n * storage: localStorage,\n * signer: () => kernl.accounts.active,\n * selfPubkey: () => kernl.accounts.active?.pubkey,\n * });\n * await backend.send({ recipients: [alice, bob], content: 'hello both' });\n * ```\n */\nexport function createGroupMessagesBackend(options: GroupMessagingOptions): MessagingBackend {\n const now = options.now ?? unixNow;\n const inboxRelays = createInboxRelays(options.store, createReplaceableLoader(options.store, options.pool, options.tiers), options.tiers);\n const store = createConversationStore();\n const subscribers = new Map<string, Subscriber>();\n const pending = new Set<Promise<unknown>>();\n let session: GroupSession | undefined;\n let subscriptionCount = 0;\n\n const deliver = (owner: string, message: DmMessage, participants: readonly string[]): DmMessage => {\n if (store.owner !== owner || !store.add(message, participants)) return message;\n for (const subscriber of subscribers.values()) {\n if (subscriber.conversationId === undefined || subscriber.conversationId === message.conversationId) subscriber.onMessage(message);\n }\n return message;\n };\n\n const context = (owner: string): GroupSessionContext => ({\n pool: options.pool,\n tiers: options.tiers,\n storage: options.storage,\n network: createGroupNetwork(options.pool, inboxRelays),\n inboxRelays,\n track(work) {\n pending.add(work);\n void work.finally(() => pending.delete(work));\n },\n deliver: (message, participants) => void deliver(owner, message, participants),\n });\n\n const signerOf = (): ISigner | undefined => (options.selfPubkey() === undefined ? undefined : options.signer());\n const close = (): void => {\n session?.close();\n session = undefined;\n store.reset();\n };\n\n const active = (): GroupSession => {\n const signer = signerOf();\n const availability = signerAvailability(signer, 'nip44');\n if (!availability.available) throw new Error(`unavailable:${availability.reason}`);\n const self = options.selfPubkey() as string;\n if (session?.self === self) return session;\n close();\n store.reset(self);\n session = openGroupSession(context(self), self, signer as ISigner);\n return session;\n };\n\n const sync = async (): Promise<void> => {\n if (!signerAvailability(signerOf(), 'nip44').available) return close();\n await active().ready;\n while (pending.size > 0) await Promise.all(pending);\n };\n\n const changes = options.accountChanges?.subscribe(() => void sync());\n\n return {\n status(): DmStatus {\n const self = options.selfPubkey();\n return {\n available: signerAvailability(signerOf(), 'nip44').available,\n ...(self === undefined ? {} : { ownerPubkey: self }),\n implementations: ['marmot'],\n capabilities: CAPABILITIES,\n };\n },\n async conversations(query) {\n await sync();\n return store.conversations(query);\n },\n async messages(query) {\n await sync();\n return store.messages(query);\n },\n async send(request) {\n const live = active();\n const client = await live.ready;\n const group =\n request.conversationId === undefined\n ? await live.groupFor(client, recipientsOf({ recipients: request.recipients, content: request.content }, live.self))\n : live.existing(client, request.conversationId);\n const rumor = createChatRumor({ pubkey: live.self, content: request.content, created_at: now() });\n const sent: DmMessage = { id: rumor.id, conversationId: groupIdOf(group), senderPubkey: live.self, createdAt: rumor.created_at, content: rumor.content, status: 'sent' };\n const message = deliver(live.self, sent, membersOf(group));\n const results = await client.groups.send(group.id, createApplicationMessageIntent(rumor)).catch(() => []);\n if (!results.some((result) => Object.values(result.response).some((response) => response.ok))) {\n store.remove(message.conversationId, message.id);\n throw new Error('unavailable:offline');\n }\n return { ok: true, message };\n },\n async subscribe(request, onMessage) {\n await sync();\n subscriptionCount += 1;\n const subscriptionId = `marmot-${subscriptionCount}`;\n subscribers.set(subscriptionId, { ...(request.conversationId === undefined ? {} : { conversationId: request.conversationId }), onMessage });\n return { subscriptionId };\n },\n unsubscribe(subscriptionId) {\n return { ok: subscribers.delete(subscriptionId) };\n },\n close() {\n changes?.unsubscribe();\n subscribers.clear();\n close();\n },\n };\n}\n","import { lastValueFrom, toArray } from 'rxjs';\nimport type { NostrEvent } from 'applesauce-core/helpers';\nimport type { NostrNetworkInterface, PublishResponse } from '@internet-privacy/marmot-ts';\nimport type { NostrFilter } from '@napplet/core';\nimport { subscribeWithEose, type ApplesaucePool } from '../applesauce/relay-hooks.js';\nimport type { InboxRelays } from './inbox-relays.js';\n\nconst asArray = <T>(value: T | T[]): T[] => (Array.isArray(value) ? value : [value]);\n\n/**\n * The group library's view of the network, over the shell's one relay pool\n * (SOUL opinion 1). A publish no relay took answers with no acknowledgements\n * rather than throwing, so the library records the failure itself; a request\n * that fails answers with no events.\n *\n * @param pool - The shell's relay pool.\n * @param inboxRelays - Where a person reads their invitations.\n * @returns A `NostrNetworkInterface` for `MarmotClient`.\n * @example\n * ```ts\n * const network = createGroupNetwork(kernl.pool, inboxRelays);\n * await network.request(['wss://relay.example'], { kinds: [30443], authors: [alice] });\n * ```\n */\nexport function createGroupNetwork(pool: ApplesaucePool, inboxRelays: InboxRelays): NostrNetworkInterface {\n return {\n async publish(relays, event) {\n const results = await pool.publish(relays, event).catch(() => []);\n return Object.fromEntries(results.map((result): [string, PublishResponse] => [result.from, { from: result.from, ok: result.ok }]));\n },\n request(relays, filters) {\n return lastValueFrom(pool.request(relays, asArray(filters)).pipe(toArray())).catch((): NostrEvent[] => []);\n },\n subscription(relays, filters) {\n return {\n subscribe(observer) {\n return subscribeWithEose(pool, relays, asArray(filters) as NostrFilter[], (item) => {\n if (item !== 'EOSE') observer.next?.(item);\n });\n },\n };\n },\n getUserInboxRelays: inboxRelays,\n };\n}\n","import { bytesToHex, kinds, mergeRelaySets, type NostrEvent } from 'applesauce-core/helpers';\nimport type { ISigner } from 'applesauce-signers';\nimport {\n ADDRESSABLE_KEY_PACKAGE_KIND,\n GROUP_EVENT_KIND,\n MarmotClient,\n deserializeApplicationData,\n getGroupMemberPubkeys,\n type MarmotGroup,\n type NostrNetworkInterface,\n} from '@internet-privacy/marmot-ts';\nimport type { DmMessage } from '@napplet/core';\nimport type { StorageLike, RelayTiers } from '../types.js';\nimport { subscribeWithEose, type ApplesaucePool, type EoseSubscription } from '../applesauce/relay-hooks.js';\nimport { createSealedGroupStore, type SealedGroupStoreOptions } from './group-storage.js';\nimport type { InboxRelays } from './inbox-relays.js';\n\n/** The chat convention the group library suggests for text; anything else carried in a group is not a message. */\nconst CHAT_KIND = 9;\n\n/** Background work that fails leaves the group as it was; the next event or send tries again. */\nconst ignore = (): undefined => undefined;\n\n/** What a group session shares with the backend that opened it. */\nexport interface GroupSessionContext {\n readonly pool: ApplesaucePool;\n readonly tiers: RelayTiers;\n readonly storage: StorageLike;\n readonly network: NostrNetworkInterface;\n readonly inboxRelays: InboxRelays;\n /** Register background work so reads can wait for it. */\n readonly track: (work: Promise<unknown>) => void;\n /** File a message the session read or wrote. */\n readonly deliver: (message: DmMessage, participants: readonly string[]) => void;\n}\n\n/** One account's group client and the subscriptions that feed it. */\nexport interface GroupSession {\n readonly self: string;\n /** Resolves once the client has loaded its groups and listens for invitations. */\n readonly ready: Promise<MarmotClient>;\n /** The group with exactly these other members, created and joined by invitation when there is none. */\n groupFor(client: MarmotClient, others: readonly string[]): Promise<MarmotGroup>;\n /** A group this device belongs to; `invalid:unknown-conversation` otherwise. */\n existing(client: MarmotClient, conversationId: string): MarmotGroup;\n close(): void;\n}\n\nasync function drain(results: AsyncIterable<unknown>): Promise<void> {\n const iterator = results[Symbol.asyncIterator]();\n while (!(await iterator.next()).done);\n}\n\nasync function openClient(network: NostrNetworkInterface, sealed: SealedGroupStoreOptions): Promise<MarmotClient> {\n const device = createSealedGroupStore<string>(sealed, 'device');\n const clientId = (await device.getItem('client-id')) ?? (await device.setItem('client-id', bytesToHex(crypto.getRandomValues(new Uint8Array(32)))));\n return new MarmotClient({\n signer: sealed.signer,\n network,\n clientId,\n groupStateStore: createSealedGroupStore(sealed, 'groups'),\n keyPackageStore: createSealedGroupStore(sealed, 'key-packages'),\n inviteStore: createSealedGroupStore(sealed, 'invites'),\n lifecycleStore: createSealedGroupStore(sealed, 'lifecycle'),\n ingestStateStore: createSealedGroupStore(sealed, 'ingest'),\n });\n}\n\n/**\n * Everyone in a group, the account included, sorted.\n *\n * @param group - A group this device belongs to.\n * @returns Member public keys.\n * @example\n * ```ts\n * membersOf(group); // ['<alice>', '<bob>']\n * ```\n */\nexport function membersOf(group: MarmotGroup): string[] {\n return getGroupMemberPubkeys(group.state).sort();\n}\n\n/**\n * A group's conversation id: its group id in hex.\n *\n * @param group - A group this device belongs to.\n * @returns The id the backend files the group's messages under.\n * @example\n * ```ts\n * groupIdOf(group); // '8f3a…'\n * ```\n */\nexport function groupIdOf(group: MarmotGroup): string {\n return bytesToHex(group.id);\n}\n\n/**\n * Start a group session for one account: open the group library over sealed\n * storage, publish a key package so others can invite the account, follow\n * the group events of every group it belongs to, and join the groups it is\n * invited to as the invitations open. Group events are applied in arrival\n * order, one group at a time, because each one moves the group's secrets on.\n *\n * @param context - Pool, tiers, storage and the backend's hooks.\n * @param self - The account's public key.\n * @param signer - The account's signer; it needs `nip44`.\n * @returns The session; `close` drops its subscriptions.\n * @example\n * ```ts\n * const session = openGroupSession(context, me, signer);\n * const client = await session.ready;\n * const group = await session.groupFor(client, [alice]);\n * ```\n */\nexport function openGroupSession(context: GroupSessionContext, self: string, signer: ISigner): GroupSession {\n const handles: EoseSubscription[] = [];\n const chains = new Map<string, Promise<void>>();\n let invites: Promise<void> = Promise.resolve();\n let closed = false;\n const groupRelays = (): string[] => mergeRelaySets(context.tiers.get().outbox, context.tiers.get().super);\n\n const receive = (group: MarmotGroup, data: Uint8Array): void => {\n const rumor = deserializeApplicationData(data);\n if (rumor.kind !== CHAT_KIND) return;\n // The library delivers only other members' messages, and an account is one member, so nothing read here is the user's own.\n const message: DmMessage = { id: rumor.id, conversationId: groupIdOf(group), senderPubkey: rumor.pubkey, createdAt: rumor.created_at, content: rumor.content, status: 'received' };\n context.deliver(message, membersOf(group));\n };\n\n const watch = (client: MarmotClient, group: MarmotGroup): void => {\n const id = groupIdOf(group);\n group.on('applicationMessage', (data) => receive(group, data));\n const filter = { kinds: [GROUP_EVENT_KIND], '#h': [bytesToHex(group.groupData?.nostrGroupId as Uint8Array)] };\n const handle = subscribeWithEose(context.pool, mergeRelaySets(group.relays), [filter], (item) => {\n if (item === 'EOSE') return;\n const next = (chains.get(id) ?? Promise.resolve()).then(() => drain(client.groups.ingest(id, [item]))).catch(ignore);\n chains.set(id, next);\n context.track(next);\n });\n handles.push(handle);\n };\n\n const publishKeyPackage = async (client: MarmotClient): Promise<void> => {\n const relays = mergeRelaySets(await context.inboxRelays(self), context.tiers.get().outbox);\n await client.keyPackages.ensurePublished({ relays }).catch(ignore);\n };\n\n const accept = (client: MarmotClient, event: NostrEvent): void => {\n invites = invites\n .then(async () => {\n if (!(await client.invites.ingestEvent(event))) return;\n await client.invites.decryptGiftWraps();\n for (const welcomeRumor of await client.invites.getUnread()) {\n await client.invites.markAsRead(welcomeRumor.id);\n watch(client, (await client.joinGroupFromWelcome({ welcomeRumor })).group);\n await publishKeyPackage(client);\n }\n })\n .catch(ignore);\n context.track(invites);\n };\n\n const start = async (): Promise<MarmotClient> => {\n const client = await openClient(context.network, { storage: context.storage, signer, owner: self });\n await publishKeyPackage(client);\n for (const group of await client.groups.loadAll()) watch(client, group);\n const relays = await context.inboxRelays(self);\n if (closed) return client;\n handles.push(\n subscribeWithEose(context.pool, relays, [{ kinds: [kinds.GiftWrap], '#p': [self] }], (item) => {\n if (item !== 'EOSE') accept(client, item);\n }),\n );\n return client;\n };\n\n const keyPackageOf = async (pubkey: string): Promise<NostrEvent> => {\n const relays = mergeRelaySets(await context.inboxRelays(pubkey), groupRelays());\n const found = await context.network.request(relays, [{ kinds: [ADDRESSABLE_KEY_PACKAGE_KIND], authors: [pubkey] }]);\n const latest = found.sort((a, b) => b.created_at - a.created_at)[0];\n if (!latest) throw new Error('unavailable:recipient-not-ready');\n return latest;\n };\n\n return {\n self,\n ready: start(),\n async groupFor(client, others) {\n const wanted = [self, ...others].sort().join(':');\n const known = client.groups.loaded.find((group) => membersOf(group).join(':') === wanted);\n if (known) return known;\n const invitees = await Promise.all(others.map(keyPackageOf));\n const group = await client.groups.create('', { relays: groupRelays(), adminPubkeys: [self], invitees });\n watch(client, group);\n return group;\n },\n existing(client, conversationId) {\n const known = client.groups.loaded.find((group) => groupIdOf(group) === conversationId);\n if (!known) throw new Error('invalid:unknown-conversation');\n return known;\n },\n close() {\n closed = true;\n for (const handle of handles) handle.unsubscribe();\n },\n };\n}\n","import { bytesToHex, hexToBytes } from 'applesauce-core/helpers';\nimport type { ISigner } from 'applesauce-signers';\nimport type { GenericKeyValueStore } from '@internet-privacy/marmot-ts';\nimport type { StorageLike } from '../types.js';\n\n/** NIP-44 encrypts at most 65535 bytes; a UTF-16 code unit takes at most three UTF-8 bytes, so 16384 units always fit. */\nconst SEAL_UNITS = 16_384;\n\n/** What {@link createSealedGroupStore} needs. */\nexport interface SealedGroupStoreOptions {\n readonly storage: StorageLike;\n /** The account signer; the store is encrypted to `owner` with its `nip44`. */\n readonly signer: ISigner;\n readonly owner: string;\n}\n\n/** The group library keeps bytes and big integers; JSON keeps neither, so both are tagged. */\nfunction encode(_key: string, value: unknown): unknown {\n if (value instanceof Uint8Array) return { $bytes: bytesToHex(value) };\n if (typeof value === 'bigint') return { $bigint: value.toString() };\n return value;\n}\n\nfunction decode(_key: string, value: unknown): unknown {\n if (value === null || typeof value !== 'object') return value;\n if ('$bytes' in value) return hexToBytes(String(value.$bytes));\n if ('$bigint' in value) return BigInt(String(value.$bigint));\n return value;\n}\n\n/**\n * One of the group library's key-value stores, sealed to the account. The\n * library keeps group secrets, its own signing keys and pending invites in\n * these stores; kernl writes each store to `storage` as one value that the\n * account signer encrypted to itself with `nip44`, split into parts NIP-44\n * can carry. Nothing readable reaches `storage`, so the key rule in\n * `SOUL.md` opinion 1 holds for every secret the library generates (D-018).\n *\n * The store is decrypted once and then served from memory, so an extension\n * or remote signer is asked once per store per page load. Writes are applied\n * in order.\n *\n * @param options - Backing storage, the account signer and its public key.\n * @param name - Which of the library's stores this is; part of the storage key.\n * @returns A `GenericKeyValueStore` for `MarmotClient`.\n * @example\n * ```ts\n * const groupStateStore = createSealedGroupStore({ storage: localStorage, signer: account, owner: account.pubkey }, 'groups');\n * await groupStateStore.setItem('note', new Uint8Array([1, 2]));\n * await groupStateStore.getItem('note'); // Uint8Array [1, 2]\n * ```\n */\nexport function createSealedGroupStore<T>(options: SealedGroupStoreOptions, name: string): GenericKeyValueStore<T> {\n const { storage, owner } = options;\n const nip44 = options.signer.nip44 as NonNullable<ISigner['nip44']>;\n const key = `kernl:group:v1:${owner}:${name}`;\n\n const open = async (): Promise<Map<string, T>> => {\n const raw = storage.getItem(key);\n if (raw === null) return new Map();\n const parts = await Promise.all((JSON.parse(raw) as string[]).map((part) => nip44.decrypt(owner, part)));\n return new Map(Object.entries(JSON.parse(parts.join(''), decode) as Record<string, T>));\n };\n const loading = open();\n let writes: Promise<unknown> = loading;\n\n const seal = async (entries: Map<string, T>): Promise<void> => {\n const text = JSON.stringify(Object.fromEntries(entries), encode);\n const parts: string[] = [];\n for (let start = 0; start < text.length; start += SEAL_UNITS) parts.push(text.slice(start, start + SEAL_UNITS));\n storage.setItem(key, JSON.stringify(await Promise.all(parts.map((part) => nip44.encrypt(owner, part)))));\n };\n const write = (change: (entries: Map<string, T>) => void): Promise<void> => {\n const next = writes.then(async () => {\n const entries = await loading;\n change(entries);\n await seal(entries);\n });\n writes = next;\n return next;\n };\n\n return {\n async getItem(item) {\n return (await loading).get(item) ?? null;\n },\n async setItem(item, value) {\n await write((entries) => entries.set(item, value));\n return value;\n },\n removeItem: (item) => write((entries) => entries.delete(item)),\n clear: () => write((entries) => entries.clear()),\n async keys() {\n return [...(await loading).keys()];\n },\n };\n}\n","import {\n createBridgeRegistry,\n createHandoffBackends,\n createHttpBridge,\n createMailBridge,\n createNzbBridge,\n createSoulseekBridge,\n createTorrentBridge,\n type BridgeRegistry,\n type BridgeRegistryOptions,\n type HandoffOpener,\n type HttpBridgeOptions,\n type TorrentBackend,\n} from '@kernlize/bridges';\n\n/** Options for {@link createDefaultBridges}. */\nexport interface DefaultBridgesOptions extends BridgeRegistryOptions {\n /** Passed to the web bridge: policy overrides, fetch and host resolver. */\n readonly http?: HttpBridgeOptions;\n /**\n * Opens a URI with an app on the user's device. When given, downloads, sharing and\n * mail resolve by handing the locator off through it; without it they report `unavailable`.\n */\n readonly handoff?: HandoffOpener;\n /**\n * The engine for magnet links, such as `createWebTorrentBackend`. It wins over the\n * hand-off for downloads from peers; the other bridges still hand off (D-017).\n */\n readonly torrent?: TorrentBackend;\n}\n\n/**\n * The shell's bridge registry: the web bridge, complete, plus the downloads, sharing\n * and mail bridges. With a `handoff` opener those four hand each locator to an app on\n * the user's device; without one they report `unavailable` (D-010). A `torrent` backend\n * replaces the hand-off for magnet links, so they download inside kernl (D-017).\n *\n * @param options - Consent hook, outcome observer, web bridge options, the hand-off opener and the torrent backend.\n * @returns A `BridgeRegistry`.\n * @example\n * ```ts\n * createDefaultBridges().forScheme('magnet')?.availability(); // { available: false, reason: 'no-backend' }\n * const bridges = createDefaultBridges({ handoff: (uri) => host.openLink(uri) });\n * bridges.forScheme('magnet')?.availability(); // { available: true, handoff: true }\n * const inKernl = createDefaultBridges({ handoff, torrent: createWebTorrentBackend({ client }) });\n * inKernl.forScheme('magnet')?.availability(); // { available: true }\n * ```\n */\nexport function createDefaultBridges(options: DefaultBridgesOptions = {}): BridgeRegistry {\n const { http, handoff, torrent, ...registryOptions } = options;\n const registry = createBridgeRegistry(registryOptions);\n const backends = handoff ? createHandoffBackends(handoff) : undefined;\n registry.register(createHttpBridge(http));\n registry.register(createTorrentBridge(torrent ?? backends?.torrent));\n registry.register(createNzbBridge(backends?.nzb));\n registry.register(createSoulseekBridge(backends?.soulseek));\n registry.register(createMailBridge(backends?.mail));\n return registry;\n}\n","import type { DmAdapter } from '@kehto/services';\nimport type { DmConversation } from '@napplet/core';\nimport type { Profiles } from '../profiles/profiles.js';\n\n/**\n * Name the people in every conversation the shell lists for an applet.\n *\n * A messaging backend knows keys; a person knows names. Each participant\n * without a label is given the name from their published profile, read from\n * the store or cache at once and otherwise looked up until it is found or\n * every lookup server has answered. A participant with no profile keeps no\n * label, so the applet still shows its own short form. A label the backend\n * already gave is kept: it is how that provider names the person (D-031).\n *\n * @param adapter - The composite messaging adapter kehto's `dm` service routes to.\n * @param profiles - The shell's profile service.\n * @returns The same adapter with participants named.\n * @example\n * ```ts\n * createDmService({ adapter: labelConversations(messaging.composite(), kernl.profiles) });\n * ```\n */\nexport function labelConversations(adapter: DmAdapter, profiles: Pick<Profiles, 'settled'>): DmAdapter {\n const named = async (conversation: DmConversation): Promise<DmConversation> => {\n const participants = await Promise.all(\n conversation.participants.map(async (peer) => {\n if (peer.label) return peer;\n const card = await profiles.settled(peer.pubkey);\n return card.found ? { ...peer, label: card.name } : peer;\n }),\n );\n return { ...conversation, participants };\n };\n return {\n ...adapter,\n async conversations(query) {\n const page = await adapter.conversations(query);\n return { ...page, conversations: await Promise.all(page.conversations.map(named)) };\n },\n };\n}\n","import { BehaviorSubject, catchError, EMPTY, endWith, firstValueFrom, ignoreElements, map, of, switchMap, type Observable } from 'rxjs';\nimport type { EventStore } from 'applesauce-core';\nimport { unixNow } from 'applesauce-core/helpers';\nimport { BLOSSOM_SERVER_LIST_KIND, getBlossomServersFromList, normalizeBlossomServer } from 'applesauce-common/helpers';\nimport type { ISigner } from 'applesauce-signers';\nimport type { NostrEvent } from '@napplet/core';\nimport type { ApplesaucePool } from '../applesauce/relay-hooks.js';\nimport { summarizePublish, type PublishOutcome } from '../relays/publish-outcome.js';\nimport type { ProfilePointer } from '../profiles/profiles.js';\n\n/**\n * File servers to use when the account has not published its own list: public\n * Blossom servers that answered an upload preflight when this was chosen.\n *\n * @example\n * ```ts\n * DEFAULT_FILE_SERVERS[0]; // 'https://blossom.primal.net/'\n * ```\n */\nexport const DEFAULT_FILE_SERVERS: readonly string[] = Object.freeze(['https://blossom.primal.net/', 'https://nostr.download/', 'https://blossom.band/']);\n\n/** Where the account's files go: its published list (BUD-03, kind 10063), or the defaults while it has none. */\nexport type FileServerState =\n | { readonly status: 'loading' }\n | { readonly status: 'missing'; readonly servers: readonly string[] }\n | { readonly status: 'found'; readonly servers: readonly string[]; readonly event: NostrEvent };\n\n/** The signed-in account's file servers. */\nexport interface AccountFileServers {\n readonly state$: Observable<FileServerState>;\n state(): FileServerState;\n /** The servers an upload goes to now: the published list once it is known, else the defaults. Waits only while the list is being looked up. */\n current(): Promise<readonly string[]>;\n /** Publish a new list. Rejects with `denied:read-only` or `invalid:server-url`. */\n save(servers: readonly string[]): Promise<PublishOutcome>;\n}\n\n/** Options for {@link createAccountFileServers}. */\nexport interface AccountFileServersOptions {\n readonly store: EventStore;\n readonly pool: Pick<ApplesaucePool, 'publish'>;\n /** Loads a replaceable event into the store and completes when the servers asked have answered. */\n readonly load: (pointer: ProfilePointer) => Observable<NostrEvent>;\n readonly pubkey$: Observable<string | undefined>;\n readonly pubkey: () => string | undefined;\n /** Where the list is looked up, and published to besides the account's outboxes. */\n readonly lookupRelays: () => readonly string[];\n /** Where the account publishes. */\n readonly outboxes: () => readonly string[];\n readonly signer: () => Pick<ISigner, 'signEvent'> | undefined;\n /** The servers used when no list is published; {@link DEFAULT_FILE_SERVERS} by default. */\n readonly defaults?: readonly string[];\n}\n\n/**\n * The servers a file-server list names, in its order, as root URLs.\n *\n * @param event - A kind 10063 list, or nothing.\n * @returns Server URLs, deduplicated.\n * @example\n * ```ts\n * fileServersFromEvent(list); // ['https://blossom.primal.net/']\n * ```\n */\nexport function fileServersFromEvent(event: NostrEvent | undefined): readonly string[] {\n return event ? [...new Set(getBlossomServersFromList(event).map((url) => url.href))] : [];\n}\n\n/**\n * The tags of a new file-server list: one `server` tag per server, in order,\n * with every other tag of the previous list kept.\n *\n * @param servers - Server URLs or hostnames.\n * @param previous - The list being replaced.\n * @returns Tags for a kind 10063 event. Throws `invalid:server-url` for something that is not a server.\n * @example\n * ```ts\n * fileServerTags(['blossom.primal.net']); // [['server', 'https://blossom.primal.net/']]\n * ```\n */\nexport function fileServerTags(servers: readonly string[], previous?: NostrEvent): string[][] {\n const urls = servers.map((server) => {\n try {\n return normalizeBlossomServer(server).href;\n } catch {\n throw new Error('invalid:server-url');\n }\n });\n const kept = (previous?.tags ?? []).filter((tag) => tag[0] !== 'server');\n return [...[...new Set(urls)].map((url) => ['server', url]), ...kept];\n}\n\nfunction stateFor(options: AccountFileServersOptions, pubkey: string | undefined): Observable<FileServerState> {\n const defaults = options.defaults ?? DEFAULT_FILE_SERVERS;\n if (pubkey === undefined) return of({ status: 'missing', servers: defaults });\n // The list is looked up until every server asked has answered; only then do the defaults stand in.\n const answered = options.load({ kind: BLOSSOM_SERVER_LIST_KIND, pubkey, relays: [...options.lookupRelays()] }).pipe(catchError(() => EMPTY), ignoreElements(), endWith(true));\n return options.store.replaceable(BLOSSOM_SERVER_LIST_KIND, pubkey).pipe(\n switchMap((event) => {\n if (event) return of<FileServerState>({ status: 'found', servers: fileServersFromEvent(event), event });\n return answered.pipe(map((): FileServerState => ({ status: 'missing', servers: defaults })));\n }),\n );\n}\n\n/**\n * Follow the active account's file-server list (BUD-03) and save a new one.\n *\n * Uploads go to these servers in order: the first gets the file, the rest\n * mirror it. An account with no published list uses the defaults. Saving signs\n * the list and publishes it to the account's outboxes and the lookup servers;\n * it succeeds when any of them accepts it (D-028).\n *\n * @param options - Store, pool, loader, account, servers and signer.\n * @returns The account's file servers.\n * @example\n * ```ts\n * const files = createAccountFileServers({ store, pool, load, pubkey$, pubkey, lookupRelays, outboxes, signer });\n * await files.current(); // ['https://blossom.primal.net/', …]\n * ```\n */\nexport function createAccountFileServers(options: AccountFileServersOptions): AccountFileServers {\n const state$ = new BehaviorSubject<FileServerState>({ status: 'loading' });\n options.pubkey$.pipe(switchMap((pubkey) => stateFor(options, pubkey))).subscribe((state) => state$.next(state));\n return {\n state$: state$.asObservable(),\n state: () => state$.value,\n current: () => firstValueFrom(state$.pipe(switchMap((state) => (state.status === 'loading' ? EMPTY : of(state.servers))))),\n async save(servers) {\n const signer = options.signer();\n const pubkey = options.pubkey();\n if (!signer || !pubkey) throw new Error('denied:read-only');\n const previous = options.store.getReplaceable(BLOSSOM_SERVER_LIST_KIND, pubkey);\n const tags = fileServerTags(servers, previous);\n const created_at = Math.max(unixNow(), (previous?.created_at ?? 0) + 1);\n const event = await signer.signEvent({ kind: BLOSSOM_SERVER_LIST_KIND, created_at, tags, content: previous?.content ?? '' });\n const relays = [...new Set([...options.outboxes(), ...options.lookupRelays()])];\n const outcome = await options.pool.publish(relays, event).then(summarizePublish, () => summarizePublish(relays.map((from) => ({ ok: false, from, message: 'publish failed' }))));\n if (outcome.ok) options.store.add(event);\n return outcome;\n },\n };\n}\n","import { Actions, computeBlobSha256, createUploadAuth, type BlobDescriptor, type SignedEvent } from 'blossom-client-sdk';\nimport type { Uploader, UploadRequest, UploadResult } from '@kehto/services';\nimport type { ISigner } from 'applesauce-signers';\nimport type { NostrEvent } from '@napplet/core';\nimport type { AppletIdentity, ConsentSummary, KernlHost } from '../types.js';\n\n/** What the person is asked about before a file leaves for a server. */\nexport interface UploadDetails {\n readonly filename?: string;\n readonly mimeType: string;\n readonly size: number;\n readonly sha256: string;\n readonly servers: readonly string[];\n}\n\n/** Uploads to several servers, the first first and the rest as mirrors; hzrd149's `multiServerUpload` fits. */\nexport type MultiServerUpload = (\n servers: readonly string[],\n blob: Blob,\n options: {\n onAuth: (server: string, sha256: string, type: 'upload' | 'media') => Promise<SignedEvent>;\n onUpload: (server: string) => void;\n onError: (server: string, sha256: string, blob: Blob, error: Error) => void;\n },\n) => Promise<Map<string, BlobDescriptor>>;\n\n/** Options for {@link createBlossomUploader}. */\nexport interface BlossomUploaderOptions {\n /** The servers this upload goes to, in order. */\n readonly servers: () => Promise<readonly string[]>;\n readonly signer: () => Pick<ISigner, 'signEvent'> | undefined;\n /** Asks the person; resolves true only when they allow it. Called once per upload, before anything is signed or sent. */\n readonly ask: (windowId: string, details: UploadDetails) => Promise<boolean>;\n /** The transfer; hzrd149's `Actions.multiServerUpload` by default. */\n readonly transfer?: MultiServerUpload;\n}\n\nconst KIB = 1024;\n\n/**\n * A size as a person reads it.\n *\n * @param bytes - A byte count.\n * @returns `512 bytes`, `1.5 KB`, `3.2 MB`.\n * @example\n * ```ts\n * sizeWords(1_572_864); // '1.5 MB'\n * ```\n */\nexport function sizeWords(bytes: number): string {\n if (bytes < KIB) return `${bytes} ${bytes === 1 ? 'byte' : 'bytes'}`;\n const units = ['KB', 'MB', 'GB'];\n let value = bytes / KIB;\n let unit = 0;\n while (value >= KIB && unit < units.length - 1) {\n value /= KIB;\n unit += 1;\n }\n return `${value.toFixed(1)} ${units[unit]}`;\n}\n\n/**\n * The consent prompt for an upload: what leaves, how big it is, where it goes\n * and who can then fetch it. A file on a public server can be fetched by\n * anyone who has its address, so the prompt says so plainly.\n *\n * @param details - The file and its servers.\n * @param applet - The applet asking.\n * @returns The summary the host renders.\n * @example\n * ```ts\n * describeUpload({ mimeType: 'image/png', size: 2048, sha256, servers }, identity).title; // 'Upload a file'\n * ```\n */\nexport function describeUpload(details: UploadDetails, applet: AppletIdentity): ConsentSummary {\n const hosts = details.servers.map((server) => new URL(server).hostname);\n const draft: NostrEvent = {\n kind: 24242,\n content: 'Upload a file',\n tags: [['t', 'upload'], ['x', details.sha256]],\n created_at: 0,\n pubkey: '',\n id: '',\n sig: '',\n };\n return {\n title: 'Upload a file',\n severity: 'public',\n lines: [\n { label: 'File', after: `${details.filename ? `${details.filename}, ` : ''}${details.mimeType}` },\n { label: 'Size', after: sizeWords(details.size) },\n { label: 'Sent to', after: hosts.join(', ') },\n { label: 'Who can see it', after: 'Anyone who has its address' },\n ],\n applet,\n event: draft,\n };\n}\n\n/**\n * Put an upload to the person through the host's consent prompt. An applet the\n * shell cannot name is refused without asking.\n *\n * @param host - Supplies `presentConsent`.\n * @param applet - The asking applet's identity, if the shell knows it.\n * @param details - The file and its servers.\n * @returns Whether the person allowed it.\n * @example\n * ```ts\n * ask: (windowId, details) => askUploadConsent(host, identityOf(windowId), details);\n * ```\n */\nexport function askUploadConsent(host: Pick<KernlHost, 'presentConsent'>, applet: AppletIdentity | undefined, details: UploadDetails): Promise<boolean> {\n if (!applet) return Promise.resolve(false);\n return new Promise((resolve) => host.presentConsent({ summary: describeUpload(details, applet), resolve }));\n}\n\nconst asBlob = (request: UploadRequest): Blob => (request.data instanceof Blob ? request.data : new Blob([request.data], request.mimeType ? { type: request.mimeType } : {}));\n\nfunction failed(uploadId: string, error: string, status: 'failed' | 'cancelled' = 'failed'): UploadResult {\n return { ok: false, uploadId, status, rail: 'blossom', error };\n}\n\nfunction completed(uploadId: string, stored: readonly BlobDescriptor[], mimeType: string): UploadResult {\n const [first, ...rest] = stored as [BlobDescriptor, ...BlobDescriptor[]];\n const type = first.type ?? mimeType;\n return {\n ok: true,\n uploadId,\n status: 'complete',\n rail: 'blossom',\n url: first.url,\n ...(rest.length ? { fallbackUrls: rest.map((descriptor) => descriptor.url) } : {}),\n sha256: first.sha256,\n size: first.size,\n mimeType: type,\n nip94: [['url', first.url], ['x', first.sha256], ['m', type], ['size', String(first.size)], ...rest.map((descriptor) => ['fallback', descriptor.url])],\n };\n}\n\n/**\n * kernl's upload backend for kehto's `createUploadService`: Blossom over\n * hzrd149's client SDK. The file goes to the account's first file server and\n * is mirrored to the others; any server that stores it makes the upload a\n * success, and the result names every copy (D-028). The person is asked first,\n * once per file, with what it is, its size and where it goes; nothing is signed\n * or sent unless they allow it. A read-only session cannot upload. An applet\n * never chooses the servers (D-033).\n *\n * @param options - Servers, signer, the consent question and an optional transfer for tests.\n * @returns An `Uploader`.\n * @example\n * ```ts\n * registry.upload = createUploadService({ uploader: createBlossomUploader({ servers: files.current, signer, ask }) });\n * ```\n */\nexport function createBlossomUploader(options: BlossomUploaderOptions): Uploader {\n const transfer: MultiServerUpload = options.transfer ?? Actions.multiServerUpload;\n return {\n async upload(request, ctx) {\n const signer = options.signer();\n if (!signer) return failed(ctx.uploadId, 'denied:read-only');\n const blob = asBlob(request);\n const servers = await options.servers();\n if (servers.length === 0) return failed(ctx.uploadId, 'unavailable:no-file-server');\n const sha256 = await computeBlobSha256(blob);\n const mimeType = blob.type || 'application/octet-stream';\n const details: UploadDetails = { mimeType, size: blob.size, sha256, servers, ...(request.filename ? { filename: request.filename } : {}) };\n if (!(await options.ask(ctx.windowId, details))) return failed(ctx.uploadId, 'denied:consent', 'cancelled');\n let auth: Promise<SignedEvent> | undefined;\n const signEvent = (draft: Parameters<ISigner['signEvent']>[0]): Promise<SignedEvent> => signer.signEvent(draft) as Promise<SignedEvent>;\n const stored = await transfer(servers, blob, {\n // One authorization covers the file on every server, so the signer is asked once.\n onAuth: (_server, hash) => (auth ??= createUploadAuth(signEvent, hash)),\n onUpload: () => {\n ctx.onStatus({ ok: true, uploadId: ctx.uploadId, status: 'uploading', rail: 'blossom', bytesSent: blob.size, bytesTotal: blob.size, updatedAt: Date.now() });\n },\n onError: () => undefined,\n }).catch(() => new Map<string, BlobDescriptor>());\n if (stored.size === 0) return failed(ctx.uploadId, `unavailable:not-accepted:0/${servers.length}`);\n return completed(ctx.uploadId, servers.flatMap((server) => stored.get(server) ?? []), mimeType);\n },\n };\n}\n","import type { ConfigServiceOptions, ConfigSettingsContext } from '@kehto/services';\nimport type { StorageLike } from '../types.js';\nimport { createNamespacedStore } from '../persistence/store.js';\n\n/** What the host shows when an applet asks for its settings. */\nexport interface SettingsPrompt {\n /** The applet's title, for the heading. */\n readonly title: string;\n /** The section the applet asked to open, if any. */\n readonly section?: string;\n /** The accepted schema, the current values and the commit that validates, saves and tells the applet. */\n readonly context: ConfigSettingsContext;\n}\n\n/** Options for {@link createAppletConfig}. */\nexport interface AppletConfigOptions {\n readonly storage: StorageLike;\n /** The applet a window runs, as a key that stays the same across its versions, with its title; none for an unknown window. */\n readonly appletOf: (windowId: string) => { readonly key: string; readonly title: string } | undefined;\n /** Shows the settings form. */\n readonly present: (prompt: SettingsPrompt) => void;\n}\n\nconst STORAGE_KEY = 'applet-config:v1';\n\n/**\n * kernl's NAP-CONFIG hooks for kehto's `createConfigService`: an applet's\n * settings, as the person set them in a form the shell draws from the\n * applet's schema. kehto validates the schema and every value. kernl keeps\n * the values per applet, not per version, so an update keeps them, and only\n * the shell's form ever writes them (D-036).\n *\n * @param options - Storage, the window-to-applet lookup and the form.\n * @returns Options for `createConfigService`.\n * @example\n * ```ts\n * registry.config = createConfigService(createAppletConfig({ storage, appletOf, present: host.presentSettings })).handler;\n * ```\n */\nexport function createAppletConfig(options: AppletConfigOptions): ConfigServiceOptions {\n const store = createNamespacedStore(options.storage, 'kernl');\n const read = (): Record<string, Record<string, unknown>> => store.getJson(STORAGE_KEY, {});\n return {\n getValues(windowId) {\n const applet = options.appletOf(windowId);\n return applet ? { ...read()[applet.key] } : {};\n },\n saveValues(windowId, values) {\n const applet = options.appletOf(windowId);\n if (applet) store.setJson(STORAGE_KEY, { ...read(), [applet.key]: values });\n },\n openSettings(windowId, section, context) {\n const applet = options.appletOf(windowId);\n if (applet) options.present({ title: applet.title, ...(section ? { section } : {}), context });\n },\n };\n}\n","import type { EventStore } from 'applesauce-core';\nimport { getProfileContent, normalizeToPubkey, unixNow } from 'applesauce-core/helpers';\nimport type { CommonServiceOptions } from '@kehto/services';\nimport type { EventTemplate, NostrEvent } from '@napplet/core';\nimport type { ISigner } from 'applesauce-signers';\nimport type { SigningConsent } from '../consent/handler.js';\nimport type { Profiles } from '../profiles/profiles.js';\n\nconst FOLLOWS = 3;\nconst REACTION = 7;\nconst REPORT = 1984;\n\n/** What the social actions need from the shell. */\nexport interface CommonActionsOptions {\n readonly store: EventStore;\n readonly profiles: Pick<Profiles, 'settled'>;\n /** The signed-in account's key, or none. */\n readonly pubkey: () => string | undefined;\n /** The account's signer, or none for a read-only session. */\n readonly signer: () => Pick<ISigner, 'signEvent'> | undefined;\n /** The shell's signing gate: destructive changes, such as a new follow list, are put to the person first. */\n readonly consent: SigningConsent;\n /** Publishes a signed event and resolves how many relays accepted it; rejects when none did (D-028). */\n readonly publish: (event: NostrEvent) => Promise<number>;\n /** Loads the account's current follow list into the store before it is changed. */\n readonly loadFollows: (pubkey: string) => Promise<void>;\n}\n\nconst reasonOf = (error: unknown): string => (error instanceof Error ? error.message : String(error));\n\nfunction followed(event: NostrEvent | undefined): string[] {\n return (event?.tags ?? []).filter((tag) => tag[0] === 'p' && typeof tag[1] === 'string').map((tag) => tag[1] as string);\n}\n\nfunction toPubkey(value: string): string | undefined {\n return normalizeToPubkey(value) ?? undefined;\n}\n\nasync function signed(options: CommonActionsOptions, windowId: string, template: EventTemplate): Promise<{ ok: true; eventId: string; event: NostrEvent } | { ok: false; error: string }> {\n const signer = options.signer();\n if (!signer) return { ok: false, error: 'denied:read-only' };\n try {\n await options.consent(windowId, template);\n const event = (await signer.signEvent(template)) as NostrEvent;\n await options.publish(event);\n options.store.add(event);\n return { ok: true, eventId: event.id, event };\n } catch (error) {\n return { ok: false, error: reasonOf(error) };\n }\n}\n\n/** The account's follow list with `pubkeys` added or removed, every other tag and the content kept. */\nasync function changeFollows(options: CommonActionsOptions, windowId: string, pubkeys: string[], add: boolean) {\n const self = options.pubkey();\n if (!self) return { ok: false, error: 'denied:read-only' };\n const targets = pubkeys.map(toPubkey);\n if (targets.some((key) => key === undefined)) return { ok: false, error: 'invalid:pubkey' };\n await options.loadFollows(self);\n const previous = options.store.getReplaceable(FOLLOWS, self);\n const current = followed(previous);\n const next = add ? [...new Set([...current, ...(targets as string[])])] : current.filter((key) => !targets.includes(key));\n const others = (previous?.tags ?? []).filter((tag) => tag[0] !== 'p');\n const tags = [...next.map((key) => ['p', key]), ...others];\n return signed(options, windowId, { kind: FOLLOWS, created_at: Math.max(unixNow(), (previous?.created_at ?? 0) + 1), tags, content: previous?.content ?? '' });\n}\n\n/**\n * kernl's NAP-COMMON hooks for kehto's `createCommonService`: profiles and\n * follows to read, and follow, unfollow, react and report to write, all on the\n * person's behalf. Reads are public data. A follow-list change replaces part\n * of the person's public record, so it passes the shell's signing gate and is\n * shown to them as what it changes; reactions and reports are posts. Every\n * write succeeds when any relay accepts it (D-028). A read-only session\n * cannot write (D-035).\n *\n * @param options - Store, profiles, account, signer, signing gate, publisher and follow-list loader.\n * @returns Options for `createCommonService`.\n * @example\n * ```ts\n * registry.common = createCommonService(createCommonActions({ store, profiles, pubkey, signer, consent, publish, loadFollows }));\n * ```\n */\nexport function createCommonActions(options: CommonActionsOptions): CommonServiceOptions {\n return {\n async getProfile(target) {\n const pubkey = toPubkey(target);\n if (!pubkey) return { ok: false, pubkey: '', error: 'invalid:pubkey' };\n const card = await options.profiles.settled(pubkey);\n const event = options.store.getReplaceable(0, pubkey);\n const content = event ? getProfileContent(event) : undefined;\n if (!card.found || !content) return { ok: true, pubkey, profile: null };\n const { display_name: displayName, ...rest } = content;\n return { ok: true, pubkey, profile: { ...rest, ...(displayName ? { displayName } : {}) } };\n },\n async follows() {\n const self = options.pubkey();\n if (!self) return { ok: false, pubkeys: [], error: 'denied:signed-out' };\n await options.loadFollows(self);\n return { ok: true, pubkeys: followed(options.store.getReplaceable(FOLLOWS, self)) };\n },\n follow: (pubkeys, context) => changeFollows(options, context.windowId, pubkeys, true),\n unfollow: (pubkeys, context) => changeFollows(options, context.windowId, pubkeys, false),\n react(targetEventId, reaction, customEmojiHref, context) {\n const target = options.store.getEvent(targetEventId);\n const emoji = customEmojiHref && /^:[\\w-]+:$/.test(reaction) ? [['emoji', reaction.slice(1, -1), customEmojiHref]] : [];\n const tags = [['e', targetEventId], ...(target ? [['p', target.pubkey], ['k', String(target.kind)]] : []), ...emoji];\n return signed(options, context.windowId, { kind: REACTION, created_at: unixNow(), tags, content: reaction });\n },\n report(target, reason, text, context) {\n const tags = target.type === 'event' ? [['e', target.id, reason], ...(target.pubkey ? [['p', target.pubkey]] : [])] : [['p', target.pubkey, reason]];\n return signed(options, context.windowId, { kind: REPORT, created_at: unixNow(), tags, content: text });\n },\n };\n}\n","import { lastValueFrom, map, takeUntil, type Observable } from 'rxjs';\nimport type { EventStore } from 'applesauce-core';\nimport type { RelayPool } from 'applesauce-relay';\nimport type { AccountManager } from 'applesauce-accounts';\nimport type { ISigner } from 'applesauce-signers';\nimport type { AddressPointerLoader } from 'applesauce-loaders/loaders';\nimport type { KernlOptions, RelayTiers } from './types.js';\nimport { isReadOnlyAccount } from './applesauce/auth-hooks.js';\nimport { createReplaceableLoader, lookupRelaysOf } from './applesauce/identity-providers.js';\nimport { connectEventCache, type ConnectedEventCache } from './cache/connect.js';\nimport { createProfiles, type Profiles } from './profiles/profiles.js';\nimport { createRelayDirectory, type RelayDirectory } from './relays/directory.js';\nimport { createAccountMailboxes, type AccountMailboxes } from './relays/mailboxes.js';\nimport { createAccountFileServers, type AccountFileServers } from './files/file-servers.js';\nimport type { CommonServiceOptions } from '@kehto/services';\nimport type { SigningConsent } from './consent/handler.js';\nimport { publishAccepted } from './applesauce/relay-backend.js';\nimport { selectRelayTier } from './applesauce/relay-hooks.js';\nimport { createCommonActions } from './social/common-actions.js';\n\n/** The parts of the shell that know people and servers: the event cache, the loader over it, profiles, mailboxes and the directory. */\nexport interface KernlNetwork {\n readonly eventCache: ConnectedEventCache;\n readonly replaceableLoader: AddressPointerLoader;\n readonly profiles: Profiles;\n readonly directory: RelayDirectory;\n readonly mailboxes: AccountMailboxes;\n readonly files: AccountFileServers;\n /** The active account's signer, or none for a read-only or signed-out session. */\n readonly signer: () => ISigner | undefined;\n}\n\n/** What {@link createKernlNetwork} composes over. */\nexport interface KernlNetworkParts {\n readonly eventStore: EventStore;\n readonly pool: RelayPool;\n readonly tiers: RelayTiers;\n readonly accounts: AccountManager;\n /** Completes the mailboxes' account stream when the shell is destroyed. */\n readonly destroyed$: Observable<void>;\n}\n\n/**\n * Compose the event cache, the replaceable loader that asks it first, the\n * profile service, the relay directory, and the active account's mailboxes\n * and file servers.\n * A read-only or signed-out session has no signer for the mailboxes, so a\n * save is refused with `denied:read-only` (D-029, D-030).\n *\n * @param options - The shell's options; `eventCache` opens the cache.\n * @param parts - The store, pool, tiers and accounts they share.\n * @returns The composed parts.\n * @example\n * ```ts\n * const network = createKernlNetwork(options, { eventStore, pool, tiers, accounts, destroyed$ });\n * network.profiles.card$(pubkey).subscribe(render);\n * ```\n */\nexport function createKernlNetwork(options: Pick<KernlOptions, 'eventCache'>, parts: KernlNetworkParts): KernlNetwork {\n const { eventStore, pool, tiers, accounts } = parts;\n const eventCache = connectEventCache(eventStore, options.eventCache);\n const replaceableLoader = createReplaceableLoader(eventStore, pool, tiers, eventCache.cacheRequest);\n const lookupRelays = (): string[] => lookupRelaysOf(tiers.get());\n const directory = createRelayDirectory({ pool });\n const signer = (): ISigner | undefined => (accounts.active && !isReadOnlyAccount(accounts.active) ? accounts.active.signer : undefined);\n const mailboxes = createAccountMailboxes({\n store: eventStore,\n pool,\n pubkey$: accounts.active$.pipe(map((account) => account?.pubkey), takeUntil(parts.destroyed$)),\n lookupRelays,\n signer,\n directory,\n });\n const profiles = createProfiles({ store: eventStore, load: replaceableLoader, lookupRelays });\n const files = createAccountFileServers({\n store: eventStore,\n pool,\n load: replaceableLoader,\n pubkey$: accounts.active$.pipe(map((account) => account?.pubkey), takeUntil(parts.destroyed$)),\n pubkey: () => accounts.active?.pubkey,\n lookupRelays,\n outboxes: () => tiers.get().outbox,\n signer,\n });\n return { eventCache, replaceableLoader, profiles, directory, mailboxes, files, signer };\n}\n\n/**\n * The social actions the shell offers applets, over the composed network:\n * profiles from the profile service, the account's follow list loaded before\n * it changes, writes signed through the signing gate and published to the\n * tier for their kind (D-035).\n *\n * @param parts - The store, pool, tiers and accounts.\n * @param network - The composed network.\n * @param consent - The shell's signing gate.\n * @returns Options for kehto's `createCommonService`.\n * @example\n * ```ts\n * createKernlServices({ ..., common: commonActionsFor(parts, network, consent) });\n * ```\n */\nexport function commonActionsFor(parts: Omit<KernlNetworkParts, 'destroyed$'>, network: Pick<KernlNetwork, 'profiles' | 'replaceableLoader' | 'signer'>, consent: SigningConsent): CommonServiceOptions {\n const { eventStore, pool, tiers, accounts } = parts;\n return createCommonActions({\n store: eventStore,\n profiles: network.profiles,\n pubkey: () => accounts.active?.pubkey,\n signer: network.signer,\n consent,\n publish: (event) => publishAccepted(pool, selectRelayTier(tiers, [{ kinds: [event.kind] }]), event),\n loadFollows: (pubkey) =>\n lastValueFrom(network.replaceableLoader({ kind: 3, pubkey, relays: lookupRelaysOf(tiers.get()) }), { defaultValue: undefined }).then(\n () => undefined,\n () => undefined,\n ),\n });\n}\n","import { catchError, distinctUntilChanged, EMPTY, endWith, filter, firstValueFrom, ignoreElements, map, merge, Observable, share, switchMap, take, timer, type Subscription } from 'rxjs';\nimport type { EventStore } from 'applesauce-core';\nimport { getDisplayName, getOutboxes, getProfileContent, getProfilePicture } from 'applesauce-core/helpers';\nimport type { NostrEvent } from '@napplet/core';\nimport { abbreviate } from '../consent/describe-change.js';\n\n/** How a person is shown: their chosen name and picture, or a short key while none is known. */\nexport interface ProfileCard {\n readonly pubkey: string;\n /** Display name, then name, then the abbreviated key. */\n readonly name: string;\n /** An `https:` picture URL, never another scheme. */\n readonly picture?: string;\n readonly nip05?: string;\n readonly about?: string;\n /** Whether a profile event has been seen; false while the name is the abbreviated key. */\n readonly found: boolean;\n}\n\n/** A replaceable pointer the loader understands. */\nexport interface ProfilePointer {\n readonly kind: number;\n readonly pubkey: string;\n readonly relays?: string[];\n}\n\n/** Loads a replaceable event into the store; applesauce's address loader fits. */\nexport type ProfileLoader = (pointer: ProfilePointer) => Observable<NostrEvent>;\n\n/** People's profiles, read from the shell's event store and loaded on demand. */\nexport interface Profiles {\n /** The card now, and again every time a newer profile arrives. Subscribing starts the lookup. */\n card$(pubkey: string): Observable<ProfileCard>;\n /** The card from what the store already holds, without asking anyone. */\n card(pubkey: string): ProfileCard;\n /** The card once the profile is found, or once the lookup servers have all answered without it; never on a timer. */\n settled(pubkey: string): Promise<ProfileCard>;\n}\n\n/** Options for {@link createProfiles}. */\nexport interface ProfilesOptions {\n readonly store: EventStore;\n readonly load: ProfileLoader;\n /** Where to look besides the author's own servers; usually the discovery and general tiers. */\n readonly lookupRelays: () => readonly string[];\n /** How long an unwatched card keeps its subscription open, in milliseconds. */\n readonly keepAliveMs?: number;\n}\n\nconst PROFILE_KIND = 0;\nconst MAILBOX_KIND = 10002;\nconst KEEP_ALIVE_MS = 60_000;\nconst HEX_KEY = /^[0-9a-f]{64}$/;\n\nfunction safePicture(event: NostrEvent): string | undefined {\n const picture = getProfilePicture(event);\n return picture?.startsWith('https://') ? picture : undefined;\n}\n\n/**\n * Read a profile card from a profile event, or the placeholder for a key with none.\n *\n * @param pubkey - The person's hex key.\n * @param event - Their newest profile event, if any.\n * @returns The card.\n * @example\n * ```ts\n * toProfileCard(pubkey, undefined).name; // '3bf0c63f…'\n * toProfileCard(pubkey, profileEvent).name; // 'fiatjaf'\n * ```\n */\nexport function toProfileCard(pubkey: string, event: NostrEvent | undefined): ProfileCard {\n const fallback = abbreviate(pubkey);\n const content = event ? getProfileContent(event) : undefined;\n if (!event || !content) return Object.freeze({ pubkey, name: fallback, found: false });\n const name = getDisplayName(content)?.trim();\n const picture = safePicture(event);\n return Object.freeze({\n pubkey,\n name: name || fallback,\n found: true,\n ...(picture ? { picture } : {}),\n ...(content.nip05 ? { nip05: content.nip05 } : {}),\n ...(content.about ? { about: content.about } : {}),\n });\n}\n\n/**\n * The profile service the shell shows people through.\n *\n * A card subscription asks the lookup relays for the person's profile and\n * their relay list at once; when the relay list names servers the profile\n * was not found on, the profile is asked for there as well, because a\n * profile lives on its author's own servers first (NIP-65). Nothing gives\n * up on a timer: a profile that arrives late replaces the placeholder.\n *\n * @param options - The store, the loader and the lookup relays.\n * @returns Profile cards per key.\n * @example\n * ```ts\n * const profiles = createProfiles({ store, load: loader, lookupRelays: () => tiers.get().discovery });\n * profiles.card$(pubkey).subscribe((card) => (label.textContent = card.name));\n * ```\n */\nexport function createProfiles(options: ProfilesOptions): Profiles {\n const { store, load } = options;\n const keepAlive = options.keepAliveMs ?? KEEP_ALIVE_MS;\n const cards = new Map<string, Observable<ProfileCard>>();\n\n const lookup = (pubkey: string): Subscription => {\n const relays = [...options.lookupRelays()];\n const subscription = load({ kind: PROFILE_KIND, pubkey, relays }).subscribe({ error: () => undefined });\n // The author's own servers, once their list is known, for a profile the lookup relays do not hold.\n const outboxes = load({ kind: MAILBOX_KIND, pubkey, relays })\n .pipe(\n map((event) => getOutboxes(event).filter((url) => !relays.includes(url))),\n filter((urls) => urls.length > 0 && !store.getReplaceable(PROFILE_KIND, pubkey)),\n take(1),\n switchMap((urls) => load({ kind: PROFILE_KIND, pubkey, relays: urls })),\n )\n .subscribe({ error: () => undefined });\n subscription.add(outboxes);\n return subscription;\n };\n\n const watch = (pubkey: string): Observable<ProfileCard> =>\n new Observable<ProfileCard>((subscriber) => {\n const loading = HEX_KEY.test(pubkey) ? lookup(pubkey) : undefined;\n const updates = store\n .replaceable(PROFILE_KIND, pubkey)\n .pipe(\n map((event) => toProfileCard(pubkey, event)),\n distinctUntilChanged((a, b) => JSON.stringify(a) === JSON.stringify(b)),\n )\n .subscribe(subscriber);\n return () => {\n updates.unsubscribe();\n loading?.unsubscribe();\n };\n }).pipe(share({ resetOnRefCountZero: () => timer(keepAlive) }));\n\n const card = (pubkey: string): ProfileCard => toProfileCard(pubkey, store.getReplaceable(PROFILE_KIND, pubkey.toLowerCase()));\n\n const profiles: Profiles = {\n card$(pubkey) {\n const key = pubkey.toLowerCase();\n let card = cards.get(key);\n if (!card) {\n card = watch(key);\n cards.set(key, card);\n }\n return card;\n },\n card,\n settled(pubkey) {\n const key = pubkey.toLowerCase();\n if (!HEX_KEY.test(key)) return Promise.resolve(card(key));\n const found = profiles.card$(key).pipe(filter((next) => next.found));\n const answered = load({ kind: PROFILE_KIND, pubkey: key, relays: [...options.lookupRelays()] }).pipe(\n catchError(() => EMPTY),\n ignoreElements(),\n endWith(undefined),\n map(() => card(key)),\n );\n return firstValueFrom(merge(found, answered));\n },\n };\n return profiles;\n}\n","import type { ServiceHandler, ServiceRuntimeContext } from '@kehto/runtime';\nimport { createCvmService, type CvmRegistryFamily, type CvmService } from '@kehto/services';\nimport { createNostrCvmTransport, type CvmRelayPool } from '@kehto/services/cvm-nostr-transport';\nimport type { NostrEvent, NostrFilter } from '@napplet/core';\nimport { publishAccepted } from '../applesauce/relay-backend.js';\nimport { subscribeWithEose, type ApplesaucePool } from '../applesauce/relay-hooks.js';\nimport type { WindowIdentities } from './window-identities.js';\n\n/** What the remote tools service needs from the shell. */\nexport interface RemoteToolsOptions {\n readonly pool: ApplesaucePool;\n /** Where a tool server is looked for when the applet names no relay for it; read when a window first calls one. */\n readonly relays: () => readonly string[];\n readonly identities: WindowIdentities;\n /** Tool families the host and the person vouch for, pinned to verified schemas; read when a window first calls one. */\n readonly registry?: () => readonly CvmRegistryFamily[];\n}\n\n/**\n * The host's tool families and the person's together. The person's family\n * takes the place of the host's with the same label and provider, so what\n * they chose is what an applet asking by that label reaches (D-043).\n *\n * @param host - Families from `KernlOptions.remoteTools.registry`.\n * @param own - Families the person trusts.\n * @returns The families the tool service offers.\n * @example\n * ```ts\n * mergeFamilies(options.remoteTools?.registry ?? [], kernl.multiplayer.state().families);\n * ```\n */\nexport function mergeFamilies(host: readonly CvmRegistryFamily[], own: readonly CvmRegistryFamily[]): CvmRegistryFamily[] {\n const key = (family: CvmRegistryFamily): string => `${family.family}:${family.server.pubkey}`;\n const chosen = new Set(own.map(key));\n return [...host.filter((family) => !chosen.has(key(family))), ...own];\n}\n\n/**\n * kehto's tool transport over the shell's one pool. A request is published to\n * every relay and succeeds when any accepts it (D-028).\n *\n * @param pool - The shared applesauce pool.\n * @returns The relay surface `createNostrCvmTransport` takes.\n * @example\n * ```ts\n * createNostrCvmTransport({ pool: createCvmRelayPool(pool), defaultRelays });\n * ```\n */\nexport function createCvmRelayPool(pool: ApplesaucePool): CvmRelayPool {\n return {\n subscribe(relays, filter, params) {\n const handle = subscribeWithEose(pool, relays, [filter as NostrFilter], (item) => {\n if (item === 'EOSE') params.oneose?.();\n else params.onevent?.(item);\n });\n return { close: () => handle.unsubscribe() };\n },\n async publish(relays, event) {\n await publishAccepted(pool, relays, event as NostrEvent);\n },\n };\n}\n\n/**\n * The `cvm` service: applets call tools on remote servers through the shell.\n *\n * Each window gets a kehto tool service of its own, with a transport that\n * calls as that window's key (D-041). Two applets that use the same server\n * neither share a client key nor receive each other's server events, and no\n * call is made as the account. When the window ends, its transport closes and\n * its key is wiped.\n *\n * @param options - Pool, default relays, window identities and an optional registry.\n * @returns The service handler to register as `cvm`.\n * @example\n * ```ts\n * registry.cvm = createRemoteToolsService({ pool, relays: () => tiers.get().super, identities });\n * ```\n */\nexport function createRemoteToolsService(options: RemoteToolsOptions): ServiceHandler {\n const windows = new Map<string, CvmService>();\n let runtime: ServiceRuntimeContext | undefined;\n const serviceFor = (windowId: string): CvmService => {\n let service = windows.get(windowId);\n if (!service) {\n const transport = createNostrCvmTransport({\n pool: createCvmRelayPool(options.pool),\n defaultRelays: [...options.relays()],\n clientSecretKey: options.identities.signer(windowId).key,\n });\n service = createCvmService({ transport, ...(options.registry ? { registry: options.registry() } : {}) });\n if (runtime) service.onRegistered?.(runtime);\n windows.set(windowId, service);\n }\n return service;\n };\n const end = (windowId: string): void => {\n const service = windows.get(windowId);\n windows.delete(windowId);\n service?.onWindowDestroyed?.(windowId);\n service?.dispose();\n options.identities.release(windowId);\n };\n return {\n descriptor: { name: 'cvm', version: '1.0.0', description: 'Remote tools, each window calling under its own key' },\n onRegistered(context) {\n runtime = context;\n },\n onUnregistered() {\n for (const windowId of windows.keys()) end(windowId);\n runtime = undefined;\n },\n handleMessage(windowId, message, send) {\n serviceFor(windowId).handleMessage(windowId, message, send);\n },\n onWindowDestroyed: end,\n onPermissionRevoked: end,\n };\n}\n","import { PrivateKeySigner } from 'applesauce-signers';\n\n/** A key per applet window that belongs to no account. */\nexport interface WindowIdentities {\n /** The window's signer, made the first time the window needs one. */\n signer(windowId: string): PrivateKeySigner;\n /** Wipe the window's key. The next use makes a new one. */\n release(windowId: string): void;\n}\n\n/**\n * Keys for the work a window does under its own name rather than the account's:\n * calling remote tools and reaching other people directly. Each window gets a\n * fresh key, so a server or a peer cannot link two applets, or one applet to\n * the account. The key lives in an applesauce signer, is never stored, and is\n * overwritten with zeros when the window ends (D-041).\n *\n * @returns The window identities.\n * @example\n * ```ts\n * const identities = createWindowIdentities();\n * const pubkey = await identities.signer('w1').getPublicKey();\n * identities.release('w1');\n * ```\n */\nexport function createWindowIdentities(): WindowIdentities {\n const signers = new Map<string, PrivateKeySigner>();\n return {\n signer(windowId) {\n let signer = signers.get(windowId);\n if (!signer) {\n signer = new PrivateKeySigner();\n signers.set(windowId, signer);\n }\n return signer;\n },\n release(windowId) {\n signers.get(windowId)?.key.fill(0);\n signers.delete(windowId);\n },\n };\n}\n","import { BehaviorSubject, type Observable } from 'rxjs';\nimport type { CvmRegistryFamily } from '@kehto/services';\nimport { createNamespacedStore } from '../persistence/store.js';\nimport type { DirectIceServer, StorageLike } from '../types.js';\n\nconst STORAGE_KEY = 'multiplayer:v1';\nconst HEX_KEY = /^[0-9a-f]{64}$/u;\nconst HELPER_URL = /^(stuns?|turns?):\\S+$/u;\nconst RELAY_URL = /^wss?:\\/\\/\\S+$/u;\n\n/** What the person chose for meeting people and calling remote tools on this device. */\nexport interface MultiplayerState {\n /** Servers that introduce people and find tool servers; undefined leaves the host's choice. */\n readonly servers?: readonly string[];\n /** Servers that help connections through; undefined leaves the host's choice. */\n readonly helpers?: readonly DirectIceServer[];\n /** Tool families the person trusts, pinned to verified schemas. */\n readonly families: readonly CvmRegistryFamily[];\n}\n\n/** The person's settings for direct connections and remote tools. */\nexport interface MultiplayerSettings {\n readonly state$: Observable<MultiplayerState>;\n state(): MultiplayerState;\n /** Choose the servers, or `undefined` to go back to the host's. Throws `invalid:relay-url`. */\n setServers(urls: readonly string[] | undefined): void;\n /** Choose the helpers, or `undefined` to go back to the host's. Throws `invalid:helper`. */\n setHelpers(helpers: readonly DirectIceServer[] | undefined): void;\n /** Trust a family, replacing one with the same label and provider. Throws `invalid:family`. */\n saveFamily(family: CvmRegistryFamily): void;\n removeFamily(label: string, pubkey: string): void;\n}\n\nconst text = (value: unknown): value is string => typeof value === 'string' && value.trim().length > 0 && value.length <= 256;\n\nfunction validServers(urls: readonly unknown[]): urls is readonly string[] {\n return urls.length <= 16 && urls.every((url) => typeof url === 'string' && RELAY_URL.test(url));\n}\n\nfunction validHelper(helper: DirectIceServer): boolean {\n return Array.isArray(helper.urls) && helper.urls.length > 0 && helper.urls.length <= 8\n && helper.urls.every((url) => typeof url === 'string' && HELPER_URL.test(url))\n && (helper.username === undefined || typeof helper.username === 'string')\n && (helper.credential === undefined || typeof helper.credential === 'string');\n}\n\n/**\n * Whether a tool family is one the shell can keep: a label, a provider key and\n * relays, and 1 to 64 uniquely named tools each pinned to a schema hash.\n *\n * @param family - A candidate family.\n * @returns True when it can be saved.\n * @example\n * ```ts\n * validFamily({ family: 'rooms', server: { pubkey, relays: ['wss://tools.example'] }, tools: [{ name: 'join', schemaHash }] }); // true\n * ```\n */\nexport function validFamily(family: CvmRegistryFamily): boolean {\n const { server, tools } = family;\n return text(family.family) && HEX_KEY.test(server.pubkey) && validServers(server.relays ?? [])\n && Array.isArray(tools) && tools.length > 0 && tools.length <= 64\n && tools.every((tool) => text(tool.name) && HEX_KEY.test(tool.schemaHash))\n && new Set(tools.map((tool) => tool.name)).size === tools.length;\n}\n\nfunction read(raw: Partial<MultiplayerState>): MultiplayerState {\n const families = Array.isArray(raw.families) ? raw.families.filter(validFamily).slice(0, 16) : [];\n return Object.freeze({\n ...(Array.isArray(raw.servers) && validServers(raw.servers) ? { servers: raw.servers } : {}),\n ...(Array.isArray(raw.helpers) && raw.helpers.every(validHelper) ? { helpers: raw.helpers } : {}),\n families,\n });\n}\n\n/**\n * The person's own settings for meeting people and calling remote tools, kept\n * on this device. They override the host's defaults: the person chooses the\n * servers that introduce them, whether anything helps their connections\n * through, and which tool families they trust (D-043). A stored value that\n * fails validation is read as unset rather than trusted.\n *\n * @param storage - Where the settings are kept, under `kernl:multiplayer:v1`.\n * @returns The settings.\n * @example\n * ```ts\n * const settings = createMultiplayerSettings(localStorage);\n * settings.setServers(['wss://meet.example']);\n * ```\n */\nexport function createMultiplayerSettings(storage: StorageLike): MultiplayerSettings {\n const store = createNamespacedStore(storage, 'kernl');\n const state$ = new BehaviorSubject<MultiplayerState>(read(store.getJson<Partial<MultiplayerState>>(STORAGE_KEY, {})));\n const commit = (next: Partial<MultiplayerState>): void => {\n const state = read(next);\n store.setJson(STORAGE_KEY, state);\n state$.next(state);\n };\n const without = (key: 'servers' | 'helpers'): Partial<MultiplayerState> => {\n const { [key]: _dropped, ...rest } = state$.value;\n return rest;\n };\n return {\n state$: state$.asObservable(),\n state: () => state$.value,\n setServers(urls) {\n if (urls && !validServers(urls)) throw new Error('invalid:relay-url');\n commit(urls ? { ...state$.value, servers: [...new Set(urls)] } : without('servers'));\n },\n setHelpers(helpers) {\n if (helpers && !(helpers.length <= 8 && helpers.every(validHelper))) throw new Error('invalid:helper');\n commit(helpers ? { ...state$.value, helpers } : without('helpers'));\n },\n saveFamily(family) {\n if (!validFamily(family)) throw new Error('invalid:family');\n const others = state$.value.families.filter((saved) => saved.family !== family.family || saved.server.pubkey !== family.server.pubkey);\n if (others.length >= 16) throw new Error('invalid:family');\n commit({ ...state$.value, families: [...others, family] });\n },\n removeFamily(label, pubkey) {\n commit({ ...state$.value, families: state$.value.families.filter((saved) => saved.family !== label || saved.server.pubkey !== pubkey) });\n },\n };\n}\n","import { lastValueFrom, takeUntil, timer, toArray } from 'rxjs';\nimport { decodeEventPointer, verifyEvent } from 'applesauce-core/helpers';\nimport { computeCvmToolSchemaHash, type CvmRegistryFamily } from '@kehto/services';\nimport type { NostrEvent, NostrFilter } from '@napplet/core';\nimport { asFilters, type ApplesaucePool } from '../applesauce/relay-hooks.js';\n\nconst KIND_SERVER = 11_316;\nconst KIND_TOOLS = 11_317;\nconst KIND_RELAY_LIST = 10_002;\nconst HASH = /^[0-9a-f]{64}$/u;\nconst MAX_BYTES = 1_000_000;\nconst MAX_TOOLS = 64;\n/**\n * How long a search waits for the servers it asked, in milliseconds.\n *\n * @example\n * ```ts\n * discoverToolFamilies(input, { pool, relays, fetch, timeoutMs: TOOL_DISCOVERY_TIMEOUT_MS / 3 });\n * ```\n */\nexport const TOOL_DISCOVERY_TIMEOUT_MS = 15_000;\n\n/** A family found for the person to review: the provider, its verified tools, and where it came from. */\nexport interface ToolFamilyCandidate {\n readonly family: CvmRegistryFamily;\n /** The announcement the inventory was read from. */\n readonly eventId: string;\n /** What the person typed, then the event. */\n readonly source: string;\n}\n\n/** What a search needs. */\nexport interface ToolDiscoveryOptions {\n readonly pool: Pick<ApplesaucePool, 'request'>;\n /** Asked when the reference names none. */\n readonly relays: readonly string[];\n /** Reads a website's published address. */\n readonly fetch: typeof fetch;\n readonly timeoutMs?: number;\n}\n\ntype Reference = { readonly type: 'hash'; readonly hash: string } | { readonly type: 'website'; readonly url: string }\n | { readonly type: 'event'; readonly id: string; readonly author?: string; readonly relays: readonly string[] };\n\nconst record = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value);\n\nfunction parseJson(text: string): unknown {\n try {\n return JSON.parse(text) as unknown;\n } catch {\n return undefined;\n }\n}\n\nfunction parse(input: string): Reference {\n const typed = input.trim().replace(/^nostr:/iu, '');\n if (HASH.test(typed.toLowerCase())) return { type: 'hash', hash: typed.toLowerCase() };\n if (/^nevent1/iu.test(typed)) {\n const pointer = decodeEventPointer(typed);\n if (!pointer || (pointer.kind !== undefined && pointer.kind !== KIND_SERVER && pointer.kind !== KIND_TOOLS)) throw new Error('invalid:tool-reference');\n // An nevent always decodes with its relay list, empty when it names none.\n return { type: 'event', id: pointer.id, ...(pointer.author ? { author: pointer.author } : {}), relays: pointer.relays as string[] };\n }\n let url: URL;\n try {\n url = new URL(typed.includes('://') ? typed : `https://${typed}`);\n } catch {\n throw new Error('invalid:tool-reference');\n }\n if (url.protocol !== 'https:' || url.username || url.password || !url.hostname.includes('.')) throw new Error('invalid:tool-reference');\n return { type: 'website', url: `${url.origin}/.well-known/napplet.json` };\n}\n\nasync function query(options: ToolDiscoveryOptions, relays: readonly string[], filter: NostrFilter): Promise<NostrEvent[]> {\n const limit = options.timeoutMs ?? TOOL_DISCOVERY_TIMEOUT_MS;\n const events = await lastValueFrom(options.pool.request([...relays], asFilters([{ ...filter, limit: MAX_TOOLS }])).pipe(takeUntil(timer(limit)), toArray()));\n return (events as NostrEvent[])\n .filter((event) => event.content.length <= MAX_BYTES && verifyEvent(event))\n .sort((a, b) => b.created_at - a.created_at);\n}\n\n/** A website's provider, from the `backend` of its `/.well-known/napplet.json`, read without credentials and at most 1 MB. */\nasync function websiteProvider(url: string, options: ToolDiscoveryOptions): Promise<{ pubkey: string; relays: string[] }> {\n const response = await options.fetch(url, { credentials: 'omit', redirect: 'error', referrerPolicy: 'no-referrer' }).catch(() => undefined);\n const body = response?.ok ? await response.text() : '';\n const document = body.length <= MAX_BYTES ? parseJson(body) : undefined;\n const backend = record(document) && document.version === 1 ? document.backend : undefined;\n if (!record(backend) || typeof backend.pubkey !== 'string' || !HASH.test(backend.pubkey) || !Array.isArray(backend.relays)) throw new Error('unavailable:website');\n return { pubkey: backend.pubkey, relays: backend.relays.filter((relay): relay is string => typeof relay === 'string') };\n}\n\n/** The tools an announcement lists, each with its hash recomputed; a hash it states that differs is a refusal. */\nasync function inventory(event: NostrEvent): Promise<CvmRegistryFamily['tools']> {\n const payload = parseJson(event.content);\n const listed = record(payload) && Array.isArray(payload.tools) ? payload.tools : [];\n if (listed.length === 0 || listed.length > MAX_TOOLS) throw new Error('invalid:tool-inventory');\n const tools: Array<{ name: string; schemaHash: string }> = [];\n for (const raw of listed as unknown[]) {\n if (!record(raw) || typeof raw.name !== 'string' || !raw.name || !record(raw.inputSchema) || tools.some((tool) => tool.name === raw.name)) throw new Error('invalid:tool-inventory');\n const schemaHash = await computeCvmToolSchemaHash({ name: raw.name, inputSchema: raw.inputSchema, ...(record(raw.outputSchema) ? { outputSchema: raw.outputSchema } : {}) });\n const tagged = event.tags.filter((tag) => tag[0] === 'i' && tag[2] === raw.name);\n if (tagged.some((tag) => tag[1] !== schemaHash)) throw new Error('invalid:tool-inventory');\n tools.push({ name: raw.name, schemaHash });\n }\n return tools;\n}\n\n/** Where a provider takes requests: its relay list's unmarked servers, else all of them, else where it was found. */\nfunction providerRelays(lists: readonly NostrEvent[], pubkey: string, found: readonly string[]): string[] {\n const listed = lists.find((list) => list.pubkey === pubkey)?.tags.filter((tag) => tag[0] === 'r' && typeof tag[1] === 'string') ?? [];\n const unmarked = listed.filter((tag) => !tag[2]);\n const chosen = (unmarked.length > 0 ? unmarked : listed).map((tag) => tag[1] as string);\n return chosen.length > 0 ? chosen : [...found];\n}\n\nasync function announcements(reference: Reference, options: ToolDiscoveryOptions): Promise<{ events: NostrEvent[]; relays: readonly string[] }> {\n if (reference.type === 'website') {\n const provider = await websiteProvider(reference.url, options);\n return { events: await query(options, provider.relays, { kinds: [KIND_TOOLS], authors: [provider.pubkey] }), relays: provider.relays };\n }\n const relays = reference.type === 'event' && reference.relays.length > 0 ? reference.relays : options.relays;\n if (reference.type === 'hash') return { events: await query(options, relays, { kinds: [KIND_TOOLS], '#i': [reference.hash] } as NostrFilter), relays };\n const found = await query(options, relays, { ids: [reference.id], kinds: [KIND_SERVER, KIND_TOOLS], ...(reference.author ? { authors: [reference.author] } : {}) });\n const first = found[0];\n if (first?.kind === KIND_SERVER) return { events: await query(options, relays, { kinds: [KIND_TOOLS], authors: [first.pubkey] }), relays };\n return { events: found, relays };\n}\n\n/**\n * Find tool families from what the person typed: a reference to a server's or\n * a tool list's announcement, a tool's schema hash, or a website that\n * publishes its provider. Only signed announcements are read; every tool's\n * hash is computed again from its schema, and an announcement whose stated\n * hash differs is refused. The newest inventory of each provider is the one\n * read, never an older one in its place (D-043).\n *\n * @param input - What the person typed.\n * @param options - Pool, default relays, and the website fetcher.\n * @returns One candidate per provider, for the person to name and save.\n * @throws `invalid:tool-reference`, `unavailable:website`, `invalid:tool-inventory`, or `unavailable:no-tools`.\n * @example\n * ```ts\n * const [candidate] = await discoverToolFamilies('nevent1…', { pool, relays: tiers.get().super });\n * settings.saveFamily({ ...candidate.family, family: 'rooms' });\n * ```\n */\nexport async function discoverToolFamilies(input: string, options: ToolDiscoveryOptions): Promise<ToolFamilyCandidate[]> {\n const reference = parse(input);\n const { events, relays } = await announcements(reference, options);\n const newest = new Map<string, NostrEvent>();\n for (const event of events) if (event.kind === KIND_TOOLS && !newest.has(event.pubkey)) newest.set(event.pubkey, event);\n if (newest.size === 0) throw new Error('unavailable:no-tools');\n const lists = reference.type === 'website' ? [] : await query(options, relays, { kinds: [KIND_RELAY_LIST], authors: [...newest.keys()] });\n const candidates: ToolFamilyCandidate[] = [];\n for (const event of newest.values()) {\n const tools = await inventory(event);\n if (reference.type === 'hash' && !tools.some((tool) => tool.schemaHash === reference.hash)) continue;\n candidates.push({\n family: { family: `tools.${event.pubkey.slice(0, 12)}`, server: { pubkey: event.pubkey, relays: providerRelays(lists, event.pubkey, relays) }, tools },\n eventId: event.id,\n source: `${input.trim()} · ${event.id.slice(0, 12)}`,\n });\n }\n if (candidates.length === 0) throw new Error('unavailable:no-tools');\n return candidates;\n}\n","import type { ApprovalOutcome, ApprovalSignal, PermissionRequirement, ServiceHandler, ServiceRuntimeContext } from '@kehto/runtime';\nimport { createWebrtcService } from '@kehto/services';\nimport type { NostrEvent } from '@napplet/core';\nimport { publishAccepted } from '../applesauce/relay-backend.js';\nimport { subscribeWithEose, type ApplesaucePool } from '../applesauce/relay-hooks.js';\nimport type { AppletIdentity, AppletSummary, ConsentSummary, DirectIceServer } from '../types.js';\nimport { createDirectSignaling, DIRECT_SIGNAL_KIND, type SignalRelay } from './direct-signaling.js';\nimport type { WindowIdentities } from './window-identities.js';\n\n/** What the direct connections service needs from the shell. */\nexport interface DirectConnectionsOptions {\n readonly pool: ApplesaucePool;\n /** Where people in a room find each other; read when a window first opens a session. */\n readonly relays: () => readonly string[];\n readonly identities: WindowIdentities;\n /** STUN and TURN servers that help connections through; read when a window first opens a session. */\n readonly iceServers: () => readonly DirectIceServer[];\n /** Makes a peer connection; the page's `RTCPeerConnection` by default. */\n readonly createPeer?: (configuration: RTCConfiguration) => RTCPeerConnection;\n /** The verified applet a window runs, or undefined. */\n readonly appletOf: (windowId: string) => Pick<AppletSummary, 'identity' | 'publisher' | 'manifest'> | undefined;\n /** Whether the person granted this window's applet direct connections, and has not blocked it. */\n readonly isGranted: (windowId: string) => boolean;\n /** Put the summary to the person; resolve true only on yes. */\n readonly ask: (summary: ConsentSummary) => Promise<boolean>;\n}\n\n/**\n * The stable address rooms are kept apart by: the publisher, the manifest\n * kind and the applet's name, the same for every version. Paja derives the\n * same string, so one applet meets the same rooms in either shell when both\n * introduce people through the same servers.\n *\n * @param summary - The verified applet.\n * @returns `<publisher>:<kind>:<name>`.\n * @example\n * ```ts\n * directNamespace(summary); // 'ab12…:35129:chess'\n * ```\n */\nexport function directNamespace(summary: Pick<AppletSummary, 'publisher' | 'manifest'>): string {\n const [, kind, ...rest] = summary.manifest.catalogId.split(':');\n if (rest[0] === summary.publisher) rest.shift();\n return `${summary.publisher}:${kind}:${rest.join(':')}`;\n}\n\n/**\n * The consent prompt for one direct session: who it reaches, what they learn\n * about the person, what the shell cannot see, and which servers introduce\n * the two sides. A direct connection hands the other side the person's\n * network address, and what passes over it is out of the shell's sight, so\n * the prompt says both plainly.\n *\n * @param requirements - What kehto's WebRTC service planned for the session.\n * @param applet - The applet asking.\n * @returns The summary the host renders.\n * @example\n * ```ts\n * describeDirectConnection(requirements, identity).title; // 'Connect directly to other people'\n * ```\n */\nexport function describeDirectConnection(requirements: readonly PermissionRequirement[], applet: AppletIdentity): ConsentSummary {\n const resource = (requirements.find((requirement) => requirement.category === 'resource') as PermissionRequirement).scope.value;\n const scoped = (kind: string): string[] => requirements.filter((requirement) => requirement.category === 'network' && requirement.scope.kind === kind).map((requirement) => requirement.scope.value);\n const relays = scoped('origin').map((origin) => new URL(origin).host);\n const helpers = scoped('ice');\n const draft: NostrEvent = { kind: DIRECT_SIGNAL_KIND, content: '', tags: [['t', 'direct']], created_at: 0, pubkey: '', id: '', sig: '' };\n return {\n title: 'Connect directly to other people',\n severity: 'direct',\n lines: [\n { label: 'With', after: resource.startsWith('room:') ? `Anyone who joins \"${resource.slice(5)}\" in this applet` : 'One person this applet chose' },\n { label: 'They learn', after: 'Your network address, which can show roughly where you are' },\n { label: 'They see', after: 'Whatever this applet sends them. The shell cannot see it.' },\n { label: 'Introduced by', after: relays.join(', ') },\n ...(helpers.length > 0 ? [{ label: 'Helped by', after: helpers.join(', ') }] : []),\n { label: 'They know you as', after: 'A new name for this window, not your account' },\n ],\n applet,\n event: draft,\n };\n}\n\nfunction signalRelayOver(pool: ApplesaucePool): SignalRelay {\n return {\n subscribe(relays, filters, onEvent) {\n const handle = subscribeWithEose(pool, [...relays], filters, (item) => {\n if (item !== 'EOSE') onEvent(item);\n });\n return { close: () => handle.unsubscribe() };\n },\n async publish(relays, event) {\n await publishAccepted(pool, [...relays], event);\n },\n };\n}\n\ninterface DirectWindow {\n readonly service: ServiceHandler;\n readonly lifetime: AbortController;\n}\n\n/**\n * The `webrtc` service: applets open direct sessions with other people.\n *\n * Each window gets kehto's WebRTC service over {@link createDirectSignaling},\n * signing under the window's own key. kehto opens a session only through the\n * runtime's approval step, which kernl supplies here instead of kehto's\n * permission authority: the window's applet must hold the `webrtc` grant, the\n * person is asked once per session, and the session's work stops when the\n * window ends, its grant changes or the person says no (D-042). Upstream\n * gap: kehto's ACL has no capability for `webrtc`, so the grant is checked\n * here, not by the ACL.\n *\n * @param options - Pool, relays, identities, ICE servers, peer factory and the grant and consent hooks.\n * @returns The service handler to register as `webrtc`.\n * @example\n * ```ts\n * registry.webrtc = createDirectConnectionsService({ pool, relays, identities, iceServers: [], createPeer, appletOf, isGranted, ask });\n * ```\n */\nexport function createDirectConnectionsService(options: DirectConnectionsOptions): ServiceHandler {\n const windows = new Map<string, DirectWindow>();\n const createPeer = options.createPeer ?? ((configuration: RTCConfiguration) => new RTCPeerConnection(configuration));\n let runtime: ServiceRuntimeContext | undefined;\n const authorize = (lifetime: ApprovalSignal) => async <T>(windowId: string, _operation: string, requirements: readonly PermissionRequirement[], execute: (signal: ApprovalSignal) => T | Promise<T>, signal?: ApprovalSignal): Promise<ApprovalOutcome<T>> => {\n const applet = options.appletOf(windowId);\n if (!applet || !options.isGranted(windowId)) return { status: 'denied' };\n if (!(await options.ask(describeDirectConnection(requirements, applet.identity)))) return { status: 'denied' };\n if (lifetime.aborted || signal?.aborted || !options.isGranted(windowId)) return { status: 'cancelled' };\n return { status: 'executed', value: await execute(lifetime) };\n };\n const windowFor = (windowId: string): DirectWindow => {\n let entry = windows.get(windowId);\n if (!entry) {\n const lifetime = new AbortController();\n const applet = options.appletOf(windowId);\n const helpers = options.iceServers();\n const configuration: RTCConfiguration = { iceServers: helpers.map((server) => ({ ...server, urls: [...server.urls] })) };\n const service = createWebrtcService(createDirectSignaling({\n signer: options.identities.signer(windowId),\n namespace: applet ? directNamespace(applet) : '',\n relays: [...options.relays()],\n relay: signalRelayOver(options.pool),\n iceEndpoints: helpers.flatMap((server) => server.urls),\n createPeer: () => createPeer(configuration),\n }));\n service.onRegistered?.({ ...runtime, authorizeOperation: authorize(lifetime.signal) } as ServiceRuntimeContext);\n entry = { service, lifetime };\n windows.set(windowId, entry);\n }\n return entry;\n };\n const end = (windowId: string): void => {\n const entry = windows.get(windowId);\n windows.delete(windowId);\n entry?.lifetime.abort();\n entry?.service.onWindowDestroyed?.(windowId);\n options.identities.release(windowId);\n };\n return {\n descriptor: { name: 'webrtc', version: '1.0.0', description: 'Direct sessions between people, each window under its own key' },\n onRegistered(context) {\n runtime = context;\n },\n onUnregistered() {\n for (const windowId of windows.keys()) end(windowId);\n runtime = undefined;\n },\n handleMessage(windowId, message, send) {\n windowFor(windowId).service.handleMessage(windowId, message, send);\n },\n onWindowDestroyed: end,\n onPermissionRevoked: end,\n };\n}\n","import { verifyEvent } from 'applesauce-core/helpers';\nimport type { WebrtcOpenPlan, WebrtcServiceContext, WebrtcServiceOptions } from '@kehto/services';\nimport type { EventTemplate, NostrEvent, NostrFilter, WebrtcEvent, WebrtcOpenRequest, WebrtcOpenResult } from '@napplet/core';\n\n/**\n * The signaling format, shared with Paja so one applet meets the same rooms in\n * either shell when both introduce people through the same servers.\n *\n * @example\n * ```ts\n * JSON.parse(signal.content).v === DIRECT_SIGNALING_PROFILE; // a hello carries the format it speaks\n * ```\n */\nexport const DIRECT_SIGNALING_PROFILE = 'soy-rtc/1';\n\n/**\n * The event kind signals travel in.\n *\n * @example\n * ```ts\n * const filter = { kinds: [DIRECT_SIGNAL_KIND], '#d': [wire] };\n * ```\n */\nexport const DIRECT_SIGNAL_KIND = 25_050;\n\n/**\n * The largest JSON payload one message may carry, in bytes.\n *\n * @example\n * ```ts\n * new TextEncoder().encode(JSON.stringify(payload)).length <= DIRECT_MAX_PAYLOAD_BYTES; // else the send is refused\n * ```\n */\nexport const DIRECT_MAX_PAYLOAD_BYTES = 16_384;\n\nconst MAX_SESSIONS = 4;\nconst MAX_PEERS = 8;\nconst HELLO_EVERY_MS = 2_000;\nconst JOIN_PATIENCE_MS = 45_000;\nconst GATHER_PATIENCE_MS = 8_000;\nconst SIGNAL_LIFETIME_S = 60;\nconst SIGNALS_PER_SECOND = 32;\nconst MESSAGES_PER_SECOND = 240;\nconst BYTES_PER_SECOND = 524_288;\nconst MAX_SIGNAL_CHARS = 64_000;\nconst MAX_SDP_CHARS = 32_000;\n/** How libwebrtc outside a browser reports a reliability limit that was never set. */\nconst UNSET_LIMIT = 65_535;\nconst HEX_KEY = /^[0-9a-f]{64}$/u;\nconst encoder = new TextEncoder();\n\n/** The window's own signer: a key that belongs to no account. */\nexport interface SignalSigner {\n getPublicKey(): Promise<string>;\n signEvent(template: EventTemplate): Promise<NostrEvent>;\n readonly nip44: { encrypt(pubkey: string, plaintext: string): Promise<string>; decrypt(pubkey: string, ciphertext: string): Promise<string> };\n}\n\n/** Where signals are published and read. */\nexport interface SignalRelay {\n subscribe(relays: readonly string[], filters: NostrFilter[], onEvent: (event: NostrEvent) => void): { close(): void };\n publish(relays: readonly string[], event: NostrEvent): Promise<void>;\n}\n\n/** What one window's direct connections run on. */\nexport interface DirectSignalingOptions {\n readonly signer: SignalSigner;\n /** The applet's stable address; rooms of different applets never meet. */\n readonly namespace: string;\n readonly relays: readonly string[];\n readonly relay: SignalRelay;\n /** STUN and TURN addresses the host configured, approved with the session. */\n readonly iceEndpoints: readonly string[];\n readonly createPeer: () => RTCPeerConnection;\n}\n\ninterface Peer {\n readonly key: string;\n readonly nonce: string;\n readonly connection: RTCPeerConnection;\n readonly started: number;\n channel?: RTCDataChannel;\n joined: boolean;\n chain: Promise<void>;\n offer?: string;\n answer?: string;\n}\n\ninterface Session {\n readonly id: string;\n readonly wire: string;\n readonly nonce: string;\n readonly request: WebrtcOpenRequest;\n readonly channel: string;\n readonly context: WebrtcServiceContext;\n readonly peers: Map<string, Peer>;\n /** Signal ids and old peer incarnations, with when they were met; forgotten once no signal of theirs can still be accepted. */\n readonly retired: Map<string, number>;\n readonly seen: Map<string, number>;\n readonly signals: { since: number; count: number };\n subscription?: { close(): void };\n timer?: ReturnType<typeof setInterval>;\n open: boolean;\n}\n\ninterface SignalBody {\n readonly v: string;\n readonly wire: string;\n readonly nonce: string;\n readonly type: 'hello' | 'offer' | 'answer';\n readonly to?: string;\n readonly sdp?: string;\n readonly realtime?: unknown;\n}\n\nfunction invalid(message: string): never {\n throw new Error(message);\n}\n\nfunction validate(request: WebrtcOpenRequest): void {\n const { scope } = request;\n if (scope.type === 'room') {\n if (typeof scope.room !== 'string' || !scope.room || scope.room.length > 256) invalid('invalid room');\n if (scope.peers && (scope.peers.length > MAX_PEERS || !scope.peers.every((key) => HEX_KEY.test(key)))) invalid('invalid peers');\n } else if (scope.type !== 'direct' || !HEX_KEY.test(scope.pubkey)) invalid('invalid scope');\n if (request.channel !== undefined && (!request.channel || request.channel.length > 64)) invalid('invalid channel');\n if (request.protocol !== undefined && request.protocol.length > 128) invalid('invalid protocol');\n}\n\n/** Only reliable, ordered delivery is offered; a peer that asks for anything else is left out. */\nfunction reliable(body: SignalBody): boolean {\n if (body.realtime === undefined) return true;\n const realtime = body.realtime as { profile?: unknown; ordered?: unknown; maxRetransmits?: unknown } | null;\n return realtime?.profile === 'soy-rtc/realtime-1' && realtime.ordered === true && realtime.maxRetransmits === null;\n}\n\nfunction reliableChannel(channel: RTCDataChannel): boolean {\n return channel.ordered && [channel.maxRetransmits, channel.maxPacketLifeTime].every((limit) => limit === null || limit === UNSET_LIMIT);\n}\n\nfunction gathered(connection: RTCPeerConnection): Promise<void> {\n return new Promise((resolve) => {\n const finish = (): void => {\n clearTimeout(timer);\n connection.removeEventListener('icegatheringstatechange', changed);\n resolve();\n };\n const changed = (): void => {\n if (connection.iceGatheringState === 'complete') finish();\n };\n const timer = setTimeout(finish, GATHER_PATIENCE_MS);\n connection.addEventListener('icegatheringstatechange', changed);\n changed();\n });\n}\n\nasync function wireOf(namespace: string, self: string, request: WebrtcOpenRequest, channel: string): Promise<string> {\n const { scope } = request;\n const where = scope.type === 'room' ? ['room', scope.room] : ['direct', ...[self, scope.pubkey].sort()];\n const identity = JSON.stringify([DIRECT_SIGNALING_PROFILE, namespace, where, channel, request.protocol ?? '']);\n const digest = await crypto.subtle.digest('SHA-256', encoder.encode(identity));\n return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('');\n}\n\n/** Forget what is older than a signal can be, so the memory a peer can fill stays bounded by the signal rate. */\nfunction forgetStale(memory: Map<string, number>, now: number): void {\n for (const [key, at] of memory) {\n if (now - at <= SIGNAL_LIFETIME_S * 1000) break;\n memory.delete(key);\n }\n}\n\n/**\n * kehto's WebRTC hooks for one window, speaking the `soy-rtc/1` signaling\n * format over the shell's pool.\n *\n * Signals are signed by the window's own key and carry the session's room\n * address, never the account. Offers and answers are encrypted to the one\n * peer they are for. Application data goes only through the data channel;\n * delivery is reliable and ordered, and a peer that asks for otherwise is\n * left out. A message is at most 16 KiB of JSON; at most four sessions per\n * window and eight peers per session (D-042).\n *\n * @param options - The window's signer and namespace, the relays, and the peer factory.\n * @returns Options for kehto's `createWebrtcService`.\n * @example\n * ```ts\n * createWebrtcService(createDirectSignaling({ signer, namespace, relays, relay, iceEndpoints: [], createPeer }));\n * ```\n */\nexport function createDirectSignaling(options: DirectSignalingOptions): WebrtcServiceOptions {\n const signaling = new DirectSignaling(options);\n return {\n planOpen: (request) => signaling.planOpen(request),\n open: (request, context) => signaling.open(request, context),\n send: (id, payload, context) => signaling.send(id, payload, context),\n close: (id, reason, context) => signaling.close(signaling.sessionFor(id, context), reason),\n destroyWindow: () => signaling.closeAll(),\n revokeWindow: () => signaling.closeAll(),\n };\n}\n\n/** One window's sessions: who is in each, what they negotiated, and the signals already heard. */\nclass DirectSignaling {\n private readonly sessions = new Map<string, Session>();\n private readonly self: Promise<string>;\n\n constructor(private readonly options: DirectSignalingOptions) {\n this.self = options.signer.getPublicKey();\n }\n\n planOpen(request: WebrtcOpenRequest): WebrtcOpenPlan {\n validate(request);\n if (this.options.relays.length === 0) invalid('signaling unavailable');\n const resource = request.scope.type === 'room' ? `room:${request.scope.room}` : `peer:${request.scope.pubkey}`;\n return { signalingRelayUrls: this.options.relays, iceEndpoints: this.options.iceEndpoints, resource };\n }\n\n async open(request: WebrtcOpenRequest, context: WebrtcServiceContext): Promise<WebrtcOpenResult> {\n validate(request);\n const me = await this.self;\n if (this.sessions.size >= MAX_SESSIONS) invalid('session limit reached');\n if (request.scope.type === 'direct' && request.scope.pubkey === me) invalid('cannot connect to self');\n const channel = request.channel ?? 'napplet';\n const wire = await wireOf(this.options.namespace, me, request, channel);\n if ([...this.sessions.values()].some((session) => session.wire === wire)) invalid('scope already open');\n const session: Session = {\n id: crypto.randomUUID(), wire, nonce: crypto.randomUUID(), request, channel, context,\n peers: new Map(), retired: new Map(), seen: new Map(), signals: { since: Date.now(), count: 0 }, open: false,\n };\n this.sessions.set(session.id, session);\n context.signal?.addEventListener('abort', () => this.close(session), { once: true });\n this.start(session);\n const { protocol } = request;\n return { session: { id: session.id, scope: request.scope, channel, ...(protocol ? { protocol } : {}), state: 'connecting' } };\n }\n\n send(id: string, payload: unknown, context: WebrtcServiceContext): void {\n const session = this.sessionFor(id, context);\n const json = JSON.stringify(payload) as string | undefined;\n const size = json === undefined ? Infinity : encoder.encode(json).length;\n if (size > DIRECT_MAX_PAYLOAD_BYTES) invalid('payload is not JSON of at most 16 KiB');\n const channels = [...session.peers.values()].filter((peer) => peer.joined && peer.channel?.readyState === 'open').map((peer) => peer.channel as RTCDataChannel);\n if (channels.length === 0) invalid('peer unavailable');\n // The browser refuses a send its queue cannot take, and that refusal is the applet's answer.\n for (const channel of channels) channel.send(json as string);\n }\n\n sessionFor(id: string, context: WebrtcServiceContext): Session {\n const session = this.sessions.get(id);\n if (!session || session.context.windowId !== context.windowId || !this.live(session)) throw new Error('session not found');\n return session;\n }\n\n close(session: Session, reason?: string): void {\n if (!this.sessions.has(session.id)) return;\n this.emit(session, { type: 'closed', sessionId: session.id, ...(reason ? { reason } : {}) });\n this.sessions.delete(session.id);\n clearInterval(session.timer);\n session.subscription?.close();\n for (const peer of session.peers.values()) this.removePeer(session, peer);\n }\n\n closeAll(): void {\n for (const session of this.sessions.values()) this.close(session);\n }\n\n private live(session: Session): boolean {\n return this.sessions.get(session.id) === session && !session.context.signal?.aborted;\n }\n\n private emit(session: Session, event: WebrtcEvent): void {\n if (this.live(session)) session.context.emit(event);\n }\n\n private activePeer(session: Session, peer: Peer): boolean {\n return this.live(session) && session.peers.get(peer.key) === peer;\n }\n\n private removePeer(session: Session, peer: Peer): void {\n if (session.peers.get(peer.key) !== peer) return;\n session.peers.delete(peer.key);\n if (peer.joined) this.emit(session, { type: 'peer', sessionId: session.id, pubkey: peer.key, state: 'left' });\n peer.channel?.close();\n peer.connection.close();\n }\n\n private async publish(session: Session, body: Partial<SignalBody>, recipient?: string): Promise<void> {\n const { signer } = this.options;\n const raw = JSON.stringify({ v: DIRECT_SIGNALING_PROFILE, wire: session.wire, nonce: session.nonce, ...body });\n const now = Math.floor(Date.now() / 1000);\n const event = await signer.signEvent({\n kind: DIRECT_SIGNAL_KIND,\n created_at: now,\n content: recipient ? await signer.nip44.encrypt(recipient, raw) : raw,\n tags: [['d', session.wire], ['expiration', String(now + SIGNAL_LIFETIME_S)], ...(recipient ? [['p', recipient]] : [])],\n });\n try {\n await this.options.relay.publish(this.options.relays, event);\n } catch {\n // No relay took it; the next hello, and the offer that goes with it, are sent again in two seconds.\n }\n }\n\n private attach(session: Session, peer: Peer, channel: RTCDataChannel): void {\n if (!this.activePeer(session, peer) || peer.channel || channel.label !== session.channel || channel.protocol !== '' || !reliableChannel(channel)) {\n channel.close();\n return;\n }\n peer.channel = channel;\n channel.addEventListener('open', () => {\n peer.joined = true;\n this.emit(session, { type: 'peer', sessionId: session.id, pubkey: peer.key, state: 'joined' });\n if (session.open) return;\n session.open = true;\n this.emit(session, { type: 'state', sessionId: session.id, state: 'open' });\n });\n const budget = { since: Date.now(), messages: 0, bytes: 0 };\n channel.addEventListener('message', (event: MessageEvent) => {\n if (!this.activePeer(session, peer) || typeof event.data !== 'string') return;\n const size = encoder.encode(event.data).length;\n if (Date.now() - budget.since > 1000) Object.assign(budget, { since: Date.now(), messages: 0, bytes: 0 });\n budget.messages += 1;\n budget.bytes += size;\n if (size > DIRECT_MAX_PAYLOAD_BYTES || budget.messages > MESSAGES_PER_SECOND || budget.bytes > BYTES_PER_SECOND) return;\n try {\n this.emit(session, { type: 'message', sessionId: session.id, from: peer.key, payload: JSON.parse(event.data) as unknown });\n } catch {\n // A peer's malformed data never reaches the applet.\n }\n });\n channel.addEventListener('close', () => this.removePeer(session, peer));\n }\n\n /** Run a peer's negotiation steps one at a time; a step that fails drops the peer. */\n private queue(session: Session, peer: Peer, step: () => Promise<void>): void {\n peer.chain = peer.chain.then(step).catch(() => this.removePeer(session, peer));\n }\n\n private async meet(session: Session, key: string, nonce: string): Promise<void> {\n const known = session.peers.get(key);\n if (known && known.nonce !== nonce) {\n // The peer reloaded: forget the old one and ignore anything it still sends.\n session.retired.set(`${key}:${known.nonce}`, Date.now());\n this.removePeer(session, known);\n } else if (known) return;\n if (session.peers.size >= MAX_PEERS) return;\n const peer: Peer = { key, nonce, connection: this.options.createPeer(), started: Date.now(), joined: false, chain: Promise.resolve() };\n session.peers.set(key, peer);\n peer.connection.addEventListener('datachannel', (event: RTCDataChannelEvent) => this.attach(session, peer, event.channel));\n peer.connection.addEventListener('connectionstatechange', () => {\n if (peer.connection.connectionState === 'failed' || peer.connection.connectionState === 'closed') this.removePeer(session, peer);\n });\n void this.publish(session, { type: 'hello' });\n if ((await this.self) < key) this.queue(session, peer, () => this.offer(session, peer));\n }\n\n private async offer(session: Session, peer: Peer): Promise<void> {\n this.attach(session, peer, peer.connection.createDataChannel(session.channel, { ordered: true }));\n await peer.connection.setLocalDescription(await peer.connection.createOffer());\n await gathered(peer.connection);\n peer.offer = (peer.connection.localDescription as RTCSessionDescription).sdp;\n await this.publish(session, { type: 'offer', to: peer.nonce, sdp: peer.offer }, peer.key);\n }\n\n private async answer(session: Session, peer: Peer, sdp: string): Promise<void> {\n if (!peer.answer) {\n await peer.connection.setRemoteDescription({ type: 'offer', sdp });\n await peer.connection.setLocalDescription(await peer.connection.createAnswer());\n await gathered(peer.connection);\n peer.answer = (peer.connection.localDescription as RTCSessionDescription).sdp;\n }\n await this.publish(session, { type: 'answer', to: peer.nonce, sdp: peer.answer }, peer.key);\n }\n\n private async negotiate(session: Session, peer: Peer, body: SignalBody): Promise<void> {\n const me = await this.self;\n const sdp = body.sdp as string;\n if (body.type === 'offer' && peer.key < me) this.queue(session, peer, () => this.answer(session, peer, sdp));\n else if (body.type === 'answer' && me < peer.key && !peer.connection.remoteDescription) {\n this.queue(session, peer, () => peer.connection.setRemoteDescription({ type: 'answer', sdp }));\n }\n }\n\n private admitted(session: Session, event: NostrEvent, me: string): boolean {\n const now = Date.now();\n forgetStale(session.seen, now);\n forgetStale(session.retired, now);\n if (now - session.signals.since > 1000) Object.assign(session.signals, { since: now, count: 0 });\n session.signals.count += 1;\n const { scope } = session.request;\n const fromAllowed = scope.type === 'direct' ? event.pubkey === scope.pubkey : !scope.peers || scope.peers.includes(event.pubkey);\n return session.signals.count <= SIGNALS_PER_SECOND\n && event.kind === DIRECT_SIGNAL_KIND\n && event.pubkey !== me\n && event.content.length <= MAX_SIGNAL_CHARS\n && Math.abs(now / 1000 - event.created_at) <= SIGNAL_LIFETIME_S\n && !session.seen.has(event.id)\n && event.tags.some((tag) => tag[0] === 'd' && tag[1] === session.wire)\n && fromAllowed\n && verifyEvent(event);\n }\n\n private async receive(session: Session, event: NostrEvent): Promise<void> {\n const me = await this.self;\n if (!this.live(session) || !this.admitted(session, event, me)) return;\n const recipient = event.tags.find((tag) => tag[0] === 'p')?.[1];\n if (recipient !== undefined && recipient !== me) return;\n session.seen.set(event.id, Date.now());\n const body = JSON.parse(recipient ? await this.options.signer.nip44.decrypt(event.pubkey, event.content) : event.content) as SignalBody;\n const shaped = body.v === DIRECT_SIGNALING_PROFILE && body.wire === session.wire && typeof body.nonce === 'string' && body.nonce.length > 0 && body.nonce.length <= 64;\n if (!shaped || session.retired.has(`${event.pubkey}:${body.nonce}`) || !reliable(body)) return;\n if (!recipient) {\n if (body.type === 'hello') await this.meet(session, event.pubkey, body.nonce);\n return;\n }\n const peer = session.peers.get(event.pubkey);\n if (!peer || peer.nonce !== body.nonce || body.to !== session.nonce || typeof body.sdp !== 'string' || body.sdp.length > MAX_SDP_CHARS) return;\n await this.negotiate(session, peer, body);\n }\n\n private start(session: Session): void {\n const filter = { kinds: [DIRECT_SIGNAL_KIND], '#d': [session.wire], since: Math.floor(Date.now() / 1000) - 10 } as NostrFilter;\n session.subscription = this.options.relay.subscribe(this.options.relays, [filter], (event) => {\n void this.receive(session, event).catch(() => undefined);\n });\n const tick = (): void => {\n void this.publish(session, { type: 'hello' });\n for (const peer of session.peers.values()) {\n if (!peer.joined && Date.now() - peer.started > JOIN_PATIENCE_MS) this.removePeer(session, peer);\n else if (peer.offer && !peer.connection.remoteDescription) void this.publish(session, { type: 'offer', to: peer.nonce, sdp: peer.offer }, peer.key);\n }\n };\n tick();\n session.timer = setInterval(tick, HELLO_EVERY_MS);\n }\n}\n","import type { EventStore } from 'applesauce-core';\nimport { verifyEvent } from 'applesauce-core/helpers';\nimport type { AuthHooks } from '@kehto/shell';\nimport type { ServiceHandler, ServiceRegistry, Signer } from '@kehto/runtime';\nimport {\n createCommonService,\n createConfigService,\n createDmService,\n createIdentityService,\n createLinkService,\n createNotifyService,\n createOutboxService,\n createRelayPoolOutboxRouter,\n createResourceService,\n createThemeService,\n createUploadService,\n type CommonServiceOptions,\n type ConfigServiceOptions,\n type DmService,\n type OutboxRouter,\n type RelayListEntry,\n type ResourceFetchInit,\n type ThemeService,\n type Uploader,\n} from '@kehto/services';\nimport type { Theme } from '@napplet/nap/theme/types';\nimport type { EventTemplate, NostrEvent } from '@napplet/core';\nimport { createBridgeResourceResolver, type BridgeContext, type BridgeRegistry, type ResourceResolveInit } from '@kernlize/bridges';\nimport type { MessagingRegistry } from '@kernlize/messaging';\nimport type { DirectConnectionsSettings, KernlHost, RelayTiers, RemoteToolsSettings } from './types.js';\nimport { createDirectConnectionsService, type DirectConnectionsOptions } from './multiplayer/direct-connections.js';\nimport { createRemoteToolsService, mergeFamilies } from './multiplayer/remote-tools.js';\nimport { createWindowIdentities, type WindowIdentities } from './multiplayer/window-identities.js';\nimport type { MultiplayerSettings } from './multiplayer/settings.js';\nimport type { ApplesaucePool } from './applesauce/relay-hooks.js';\nimport { createAppletRelayService, createOutboxRelayPool } from './applesauce/relay-backend.js';\nimport { createIdentityProviders, type IdentityProviders, type RelayPermissions } from './applesauce/identity-providers.js';\nimport type { SigningConsent, SigningTemplate } from './consent/handler.js';\nimport { labelConversations } from './messaging/label-conversations.js';\nimport type { Profiles } from './profiles/profiles.js';\n\n/**\n * Whether a host-supplied theme has the colours NAP-THEME requires.\n *\n * @param value - The `theme` option as the host passed it.\n * @returns True when `colors.background`, `colors.text` and `colors.primary` are strings.\n * @example\n * ```ts\n * isTheme({ colors: { background: '#000', text: '#fff', primary: '#7aa2f7' } }); // true\n * ```\n */\nexport function isTheme(value: Record<string, unknown> | undefined): value is Record<string, unknown> & Theme {\n const colors = value?.colors;\n if (typeof colors !== 'object' || colors === null) return false;\n const { background, text, primary } = colors as Record<string, unknown>;\n return typeof background === 'string' && typeof text === 'string' && typeof primary === 'string';\n}\n\n/**\n * Protocols an applet may ask the shell to open.\n *\n * @example\n * ```ts\n * LINK_PROTOCOLS.includes(new URL('mailto:a@example.com').protocol); // true\n * LINK_PROTOCOLS.includes('javascript:'); // false\n * ```\n */\nexport const LINK_PROTOCOLS: readonly string[] = Object.freeze(['https:', 'mailto:']);\n\n/** What the services need from the rest of the shell. */\nexport interface KernlServiceDeps {\n readonly pool: ApplesaucePool;\n readonly tiers: RelayTiers;\n readonly eventStore: EventStore;\n /** `getUserPubkey` lets the identity service name a read-only account, which has no signer. */\n readonly auth: Pick<AuthHooks, 'getSigner'> & Partial<Pick<AuthHooks, 'getUserPubkey'>>;\n /** Gates the outbox service's publishes, which kehto signs without naming the window. */\n readonly consent: SigningConsent;\n readonly host: Pick<KernlHost, 'notify' | 'openLink'>;\n readonly bridges: BridgeRegistry;\n readonly messaging: MessagingRegistry;\n /** Applet settings (NAP-CONFIG); without them the `config` domain is not offered. */\n readonly config?: ConfigServiceOptions;\n /** Social actions for applets (NAP-COMMON); without them the `common` domain is not offered. */\n readonly common?: CommonServiceOptions;\n /** Uploads for applets (NAP-UPLOAD); without it the `upload` domain is not offered. */\n readonly uploader?: Uploader;\n /** Names conversation participants for applets; without it they are listed by key alone. */\n readonly profiles?: Pick<Profiles, 'settled'>;\n readonly theme?: Theme;\n /** Maps a live window to its verified identity, or null. */\n readonly resolveIdentity: (windowId: string) => { dTag: string; aggregateHash: string } | null;\n /** Identity lookups; defaults to the applesauce-backed providers. */\n readonly identity?: IdentityProviders;\n /** Keys for the work a window does under its own name; a fresh set by default (D-041). */\n readonly identities?: WindowIdentities;\n /** Where remote tools are looked for and which families the host vouches for. */\n readonly remoteTools?: RemoteToolsSettings | undefined;\n /** Direct connections; without them the `webrtc` domain is not offered (D-042). */\n readonly directConnections?: DirectConnectionsDeps | undefined;\n /** The person's own choices, which come before the host's (D-043). */\n readonly multiplayer?: Pick<MultiplayerSettings, 'state'>;\n}\n\n/** What the `webrtc` service needs beyond the pool and the window identities. */\nexport interface DirectConnectionsDeps extends Pick<DirectConnectionsOptions, 'createPeer' | 'appletOf' | 'isGranted' | 'ask'> {\n readonly settings: Omit<DirectConnectionsSettings, 'createPeer'>;\n}\n\n/** The registered services plus the handles the shell keeps calling. */\nexport interface KernlServices {\n readonly registry: ServiceRegistry;\n readonly theme: ThemeService;\n readonly dm: DmService;\n}\n\nfunction toRelayListEntry(relays: RelayPermissions): RelayListEntry {\n const entries = Object.entries(relays);\n return {\n read: entries.filter(([, flags]) => flags.read).map(([url]) => url),\n write: entries.filter(([, flags]) => flags.write).map(([url]) => url),\n };\n}\n\nfunction withShellWrites(entry: RelayListEntry, tiers: KernlServiceDeps['tiers']): RelayListEntry {\n const { outbox, super: shared } = tiers.get();\n return { read: entry.read, write: [...new Set([...outbox, ...shared])] };\n}\n\n/**\n * kehto's outbox router fails a publish unless every one of the author's\n * write relays accepted it. On an open network one server refusing or being\n * down is ordinary, so kernl reports success when any relay accepted, and\n * keeps the per-relay results so the caller sees how many did (D-028).\n * Upstream gap: the router has no acceptance policy option.\n *\n * @param router - kehto's outbox router.\n * @returns The same router with partial acceptance treated as success.\n * @example\n * ```ts\n * createOutboxService({ router: acceptAnyRelay(createRelayPoolOutboxRouter(options)) });\n * ```\n */\nexport function acceptAnyRelay(router: OutboxRouter): OutboxRouter {\n return {\n ...router,\n async publish(template, options) {\n const result = await router.publish(template, options);\n if (result.ok || !result.relays || !Object.values(result.relays).some(Boolean)) return result;\n const { error: _refused, ...accepted } = result;\n return { ...accepted, ok: true };\n },\n };\n}\n\nfunction requesterFor(deps: Pick<KernlServiceDeps, 'resolveIdentity'>, windowId: string | undefined): BridgeContext['requester'] {\n const identity = windowId === undefined ? null : deps.resolveIdentity(windowId);\n return identity ? { dTag: identity.dTag, hash: identity.aggregateHash } : 'shell';\n}\n\n/**\n * Translate the resource service's fetch init into the bridge resolver's,\n * naming the applet that asked so the bridge consent hook can see it.\n *\n * @param deps - Supplies the window-to-identity lookup.\n * @param init - What kehto's resource service passes to `fetch`.\n * @returns The init for `createBridgeResourceResolver`'s resolver.\n * @example\n * ```ts\n * resourceInitFor(deps, { signal, windowId: 'w1' }).requester; // { dTag: 'chat', hash: '…' }\n * ```\n */\nexport function resourceInitFor(deps: Pick<KernlServiceDeps, 'resolveIdentity'>, init: ResourceFetchInit): ResourceResolveInit {\n const requester = requesterFor(deps, init.windowId);\n return init.headers ? { signal: init.signal, requester, headers: init.headers } : { signal: init.signal, requester };\n}\n\n/**\n * The signer the identity service reads the account from. A read-only account\n * has no signer, yet which account is signed in is exactly what it exists to\n * show, so the service gets a view that answers `getPublicKey` and nothing\n * else: an applet the user granted \"your account\" learns who is signed in, and\n * every write still finds no `signEvent` and is refused.\n */\nfunction createIdentitySigner(auth: KernlServiceDeps['auth']): () => Signer | null {\n // The identity service drops a reply when the signer object changed under\n // it, so a read-only account keeps one view for as long as it is signed in.\n let view: { readonly pubkey: string; readonly signer: Signer } | undefined;\n return () => {\n const signer = auth.getSigner();\n if (signer) return signer;\n const pubkey = auth.getUserPubkey?.() ?? null;\n if (pubkey === null) return null;\n if (view?.pubkey !== pubkey) view = { pubkey, signer: { getPublicKey: () => pubkey } };\n return view.signer;\n };\n}\n\nfunction createOutbox(deps: KernlServiceDeps, identity: IdentityProviders) {\n const router = createRelayPoolOutboxRouter({\n relayPool: createOutboxRelayPool(deps.pool),\n fallbackRelays: [...deps.tiers.get().super],\n async loadRelayLists(pubkeys) {\n const lists = new Map<string, RelayListEntry>();\n for (const pubkey of pubkeys) {\n const entry = toRelayListEntry(await identity.getRelays(pubkey));\n // Someone who has not said where they write is read from, and publishes to, the servers this shell writes to.\n lists.set(pubkey, entry.write.length === 0 ? withShellWrites(entry, deps.tiers) : entry);\n }\n return lists;\n },\n async signEvent(template: EventTemplate): Promise<NostrEvent> {\n const signer = deps.auth.getSigner();\n if (!signer?.signEvent) throw new Error('denied:read-only');\n return signer.signEvent(template);\n },\n verifyEvent: (event) => verifyEvent(event),\n });\n return createOutboxService({ router: acceptAnyRelay(router) });\n}\n\n/**\n * Put the outbox service's publishes through the consent gate.\n *\n * kehto's outbox router signs through a `signEvent` that is not told which\n * window asked, so the gate cannot sit at the signer as it does for `relay`.\n * It sits in front of the service instead, where the window is still known:\n * the publish reaches the router only after the gate resolves.\n *\n * @param outbox - kehto's outbox service.\n * @param consent - The signing consent gate.\n * @returns The same service with `outbox.publish` gated.\n * @example\n * ```ts\n * registry.outbox = gateOutboxPublish(createOutboxService({ router }), consent);\n * ```\n */\nfunction gateOutboxPublish(outbox: ServiceHandler, consent: SigningConsent): ServiceHandler {\n return {\n ...outbox,\n handleMessage(windowId, message, send) {\n if (message.type !== 'outbox.publish') {\n outbox.handleMessage(windowId, message, send);\n return;\n }\n const { id, event } = message as { id?: string; event?: SigningTemplate | null };\n consent(windowId, event ?? {}).then(\n () => outbox.handleMessage(windowId, message, send),\n (error: Error) => {\n const refusal = { type: 'outbox.publish.result', id: id ?? '', ok: false, error: error.message };\n send(refusal);\n },\n );\n },\n };\n}\n\n/**\n * Register kehto's reference services over the shell's applesauce layer.\n *\n * `relay`, `identity`, `theme`, `notify`, `link`, `resource`, `dm`, `outbox`\n * and `cvm` are wired; every network path goes through the one pool, every\n * resource fetch through the bridge registry's SSRF policy, links open only\n * over `https:` and `mailto:`, notifications surface through the host, outbox\n * publishes pass the consent gate before they are signed, and remote tools are\n * called under each window's own key.\n *\n * @param deps - Pool, tiers, store, auth, consent gate, host, registries and identity resolver.\n * @returns The service registry and the theme and dm handles.\n * @example\n * ```ts\n * const services = createKernlServices(deps);\n * const adapter: ShellAdapter = { ..., services: services.registry };\n * ```\n */\nexport function createKernlServices(deps: KernlServiceDeps): KernlServices {\n const identity = deps.identity ?? createIdentityProviders(deps.eventStore, deps.pool, deps.tiers);\n const theme = createThemeService(deps.theme ? { initialTheme: deps.theme } : {});\n const composite = deps.messaging.composite();\n const dm = createDmService({ adapter: deps.profiles ? labelConversations(composite, deps.profiles) : composite });\n const resolve = createBridgeResourceResolver(deps.bridges);\n const identities = deps.identities ?? createWindowIdentities();\n const direct = deps.directConnections;\n const chosen = () => deps.multiplayer?.state();\n\n const registry: ServiceRegistry = {\n relay: createAppletRelayService(deps.pool, deps.tiers),\n identity: createIdentityService({ getSigner: createIdentitySigner(deps.auth), ...identity }),\n theme: theme.handler,\n notify: createNotifyService({\n present: ({ windowId, message }) => deps.host.notify({ title: message.title, windowId, tone: 'info', ...(message.body ? { body: message.body } : {}) }),\n }),\n link: createLinkService({\n allowedProtocols: LINK_PROTOCOLS,\n open: ({ url }) => {\n deps.host.openLink(url.href);\n return { status: 'opened' };\n },\n }),\n resource: createResourceService({\n fetch: (url, init) => resolve(url, resourceInitFor(deps, init)),\n }),\n dm,\n outbox: gateOutboxPublish(createOutbox(deps, identity), deps.consent),\n cvm: createRemoteToolsService({\n pool: deps.pool,\n relays: () => chosen()?.servers ?? deps.remoteTools?.relays ?? deps.tiers.get().super,\n identities,\n registry: () => mergeFamilies(deps.remoteTools?.registry ?? [], chosen()?.families ?? []),\n }),\n ...(direct ? {\n webrtc: createDirectConnectionsService({\n ...direct,\n pool: deps.pool,\n relays: () => chosen()?.servers ?? direct.settings.relays ?? deps.tiers.get().super,\n identities,\n iceServers: () => chosen()?.helpers ?? direct.settings.iceServers ?? [],\n }),\n } : {}),\n ...(deps.config ? { config: createConfigService(deps.config).handler } : {}),\n ...(deps.common ? { common: createCommonService(deps.common) } : {}),\n ...(deps.uploader ? { upload: createUploadService({ uploader: deps.uploader, uploadInfo: { rails: [{ rail: 'blossom', enabled: true }] } }) } : {}),\n };\n return { registry, theme, dm };\n}\n","import type { AccountManager } from 'applesauce-accounts';\nimport { verifyEvent } from 'applesauce-core/helpers';\nimport type { CapabilityHooks, NappletRevocation, ShellAdapter, UnroutedMessageInfo } from '@kehto/shell';\nimport type { ServiceRegistry } from '@kehto/runtime';\nimport type { RelayTier, RelayTiers } from './types.js';\nimport { createAuthHooks } from './applesauce/auth-hooks.js';\nimport type { SigningConsent } from './consent/handler.js';\nimport { createRelayPoolHooks, type ApplesaucePool } from './applesauce/relay-hooks.js';\nimport type { RuntimeFirewallHooks } from './guard/runtime-rules.js';\n\nconst TIERS: readonly string[] = ['discovery', 'apps', 'outbox', 'super'];\n\n/** What the adapter needs from the rest of the shell. */\nexport interface ShellAdapterDeps {\n readonly pool: ApplesaucePool;\n readonly tiers: RelayTiers;\n readonly accounts: AccountManager;\n /** Gates every signature made for an applet window; see `createSigningConsent`. */\n readonly consent: SigningConsent;\n readonly services: ServiceRegistry;\n readonly resolveEnvironment: NonNullable<CapabilityHooks['resolveEnvironment']>;\n readonly onNappletRevoked: (revocation: NappletRevocation) => void;\n /** Decides every port envelope before kehto's runtime sees it; see `GuardPipeline.observe`. */\n readonly filterNappletMessage: NonNullable<ShellAdapter['filterNappletMessage']>;\n /** Whether a window has focus, as the shell's window manager reports it. */\n readonly getFocusContext: (windowId: string) => { focused: boolean };\n /** The runtime firewall's persistence and event sink; see `createRuntimeFirewallHooks`. */\n readonly runtimeFirewall: RuntimeFirewallHooks;\n readonly onUnroutedMessage?: (info: UnroutedMessageInfo) => void;\n}\n\nconst UPLOAD_BACKEND = Object.freeze({ rails: Object.freeze(['blossom']) });\n\nfunction isTier(tier: string): tier is RelayTier {\n return TIERS.includes(tier);\n}\n\n/**\n * Build kehto's `ShellAdapter` from kernl's parts.\n *\n * Choices kehto left open, decided here: windows are created by the host,\n * which opens an intent's target for it, not by applets (`createWindow`\n * returns null); the `intent` domain is offered, served by kernl's router; hotkeys are\n * not forwarded; there is no worker relay, the applesauce pool is the only\n * event source; every signature made for an applet window passes the consent\n * gate; update behaviour is `banner`; event signatures are verified by\n * applesauce; every applet's environment is narrowed by the grants layer; the\n * ACL is restrictive, so an applet holds only what the grants layer wrote; and\n * every port envelope passes kernl's guard before the runtime sees it.\n *\n * @param deps - Pool, tiers, accounts, services and the shell's hooks.\n * @returns The adapter for `createShellBridge`.\n * @example\n * ```ts\n * const bridge = createShellBridge(createShellAdapter(deps));\n * ```\n */\nexport function createShellAdapter(deps: ShellAdapterDeps): ShellAdapter {\n const { tiers } = deps;\n return {\n relayPool: createRelayPoolHooks(deps.pool, tiers),\n relayConfig: {\n addRelay(tier, url) {\n if (isTier(tier)) tiers.add(tier, url);\n },\n removeRelay(tier, url) {\n if (isTier(tier)) tiers.remove(tier, url);\n },\n getRelayConfig() {\n const config = tiers.get();\n return { discovery: [...config.discovery], super: [...config.super], outbox: [...config.outbox] };\n },\n getNip66Suggestions: () => null,\n },\n windowManager: { createWindow: () => null },\n auth: createAuthHooks(deps.accounts, deps.consent),\n config: { getNappUpdateBehavior: () => 'banner' },\n hotkeys: { executeHotkeyFromForward: () => undefined },\n workerRelay: { getWorkerRelay: () => null },\n // kehto offers the upload domain only when both the service and this backend are present; kernl's uploads are Blossom (D-033).\n upload: { getUploader: () => (deps.services.upload ? UPLOAD_BACKEND : null) },\n common: { isAvailable: () => deps.services.common !== undefined },\n // kehto offers direct connections only when this says so; kernl registers the service only where the page can make peer connections (D-042).\n webrtc: { isAvailable: () => deps.services.webrtc !== undefined },\n crypto: { verifyEvent: (event) => Promise.resolve(verifyEvent(event)) },\n link: { isAvailable: () => true },\n intent: { isAvailable: () => true },\n services: deps.services,\n capabilities: { resolveEnvironment: deps.resolveEnvironment },\n onNappletRevoked: deps.onNappletRevoked,\n filterNappletMessage: deps.filterNappletMessage,\n getFocusContext: deps.getFocusContext,\n ...deps.runtimeFirewall,\n aclDefaultPolicy: 'restrictive',\n ...(deps.onUnroutedMessage ? { onUnroutedMessage: deps.onUnroutedMessage } : {}),\n };\n}\n","import type { Subscription } from 'rxjs';\nimport { originRegistry, type ShellAdapter, type ShellBridge } from '@kehto/shell';\nimport type { NappletArtifactCache } from '@kehto/nip/5d';\nimport type { AppletHandle, AppletIdentity, AppletPointer, AppletSummary, BuiltinApplet, FrameLike, GrantRecord, Kernl, KernlHost, MountPlan, RelayTiers } from './types.js';\nimport type { ApplesaucePool } from './applesauce/relay-hooks.js';\nimport { resolveBuiltin } from './applets/builtin.js';\nimport { fetchManifestEvent, resolveApplet, type PublishedPointer, type ResolvedApplet } from './applets/resolve.js';\nimport { planMount } from './applets/plan.js';\nimport { mountApplet, type MountedApplet } from './applets/mount.js';\nimport type { GuardPipeline, WindowResolution } from './guard/pipeline.js';\nimport { applyRuntimeFirewallRules, type RuntimeFirewallState } from './guard/runtime-rules.js';\nimport type { KernlGrants } from './grants/grants.js';\nimport type { InstalledApplets } from './intents/installed.js';\n\n/** What the applet lifecycle needs from the composed shell. */\nexport interface LifecycleContext {\n readonly pool: ApplesaucePool;\n readonly tiers: RelayTiers;\n readonly adapter: ShellAdapter;\n readonly bridge: ShellBridge;\n readonly pipeline: GuardPipeline;\n /** The runtime firewall kernl constructed; mounting installs the applet's rates in it. */\n readonly firewall: RuntimeFirewallState;\n readonly grants: KernlGrants;\n /** Every planned applet is installed, so others can hand it work. */\n readonly installed: InstalledApplets;\n readonly host: Pick<KernlHost, 'onRevoked'>;\n /** Live handles keyed by window id; shared with the bridge's revocation hook. */\n readonly handles: Map<string, MountedApplet>;\n readonly subscriptions: Subscription;\n readonly openCache: () => Promise<NappletArtifactCache | undefined>;\n readonly fetchBlob: (sha256: string, servers: readonly string[]) => Promise<Uint8Array>;\n /** Applets the host ships with itself. */\n readonly builtins: readonly BuiltinApplet[];\n}\n\n/**\n * Why a grant change stops a running window, or nothing when it does not.\n *\n * A window keeps the environment it was started with, and `shell.init` is not\n * sent again, so a window whose grant no longer covers a domain it was started\n * with would go on advertising it. Granting more never stops a window; the\n * applet sees the new domain the next time it opens.\n *\n * @param plan - The running window's plan; its environment is what it was started with.\n * @param record - The grant record that just changed.\n * @param baseline - Domains every applet holds, from `grants.baselineDomains()`.\n * @returns `blocked`, `grant-narrowed`, or `undefined` when the window may keep running.\n * @example\n * ```ts\n * grants.changes$.subscribe((record) => {\n * const reason = grantNarrowingReason(plan, record, grants.baselineDomains());\n * if (reason) handle.revoked(reason);\n * });\n * ```\n */\nexport function grantNarrowingReason(plan: MountPlan, record: GrantRecord, baseline: readonly string[]): 'blocked' | 'grant-narrowed' | undefined {\n const { identity } = plan.summary;\n if (record.identity.dTag !== identity.dTag || record.identity.hash !== identity.hash) return undefined;\n if (record.blocked) return 'blocked';\n const allowed = new Set([...baseline, ...record.domains]);\n return plan.environment.capabilities.domains.some((domain) => !allowed.has(domain)) ? 'grant-narrowed' : undefined;\n}\n\n/** The applet half of {@link Kernl}. */\nexport type AppletLifecycle = Pick<Kernl, 'resolve' | 'install' | 'plan' | 'mount' | 'applets' | 'handleWindowMessage'>;\n\nfunction keyOf(identity: AppletIdentity): string {\n return `${identity.dTag}:${identity.hash}`;\n}\n\n/**\n * Resolve the window a window-level message came from, from the shell's own\n * registry and never from the message.\n *\n * @param handles - Live applet handles.\n * @param event - The window-level message.\n * @returns The window and its applet, or null for unregistered sources.\n * @example\n * ```ts\n * resolveWindow(handles, event)?.napplet; // 'chat'\n * ```\n */\nexport function resolveWindow(handles: ReadonlyMap<string, MountedApplet>, event: MessageEvent): WindowResolution | null {\n const windowId = event.source ? originRegistry.getWindowId(event.source as Window) : undefined;\n const handle = windowId === undefined ? undefined : handles.get(windowId);\n return windowId !== undefined && handle ? { windowId, napplet: handle.summary.identity.dTag } : null;\n}\n\n/**\n * Load a built-in applet and, the first time the user meets it, switch on the domains its host\n * vouches for. A domain this shell cannot provide is skipped, and an applet the user already has\n * a record for is left exactly as they set it.\n */\nasync function resolveShipped(context: LifecycleContext, id: string): Promise<ResolvedApplet> {\n const resolved = await resolveBuiltin(context.builtins, id);\n const { identity } = resolved.summary;\n if (context.grants.get(identity)) return resolved;\n context.grants.ensure(identity);\n const offered = context.grants.availableDomains();\n const wanted = context.builtins.find((applet) => applet.id === id)?.grants ?? [];\n for (const domain of wanted) if (offered.includes(domain)) context.grants.allowDomain(identity, domain);\n return resolved;\n}\n\n/**\n * The applet lifecycle: `resolve` fetches and verifies (or loads an applet the host ships), `plan` narrows the\n * environment under the user's grants and installs the applet, `mount` performs the NIP-5D mount order\n * and `handleWindowMessage` runs the guard in front of the bridge.\n *\n * @param context - The composed shell's parts.\n * @returns The lifecycle methods.\n * @example\n * ```ts\n * const lifecycle = createAppletLifecycle(context);\n * const summary = await lifecycle.resolve(pointer);\n * ```\n */\nexport function createAppletLifecycle(context: LifecycleContext): AppletLifecycle {\n const { handles, pipeline, bridge } = context;\n const verified = new Map<string, string>();\n let windowCounter = 0;\n const lookUp = async (pointer: PublishedPointer): Promise<ResolvedApplet> => {\n const event = await fetchManifestEvent(context.pool, context.tiers, pointer);\n const cache = await context.openCache();\n const { fetchBlob } = context;\n const relays = pointer.relays;\n return resolveApplet(cache ? { event, fetchBlob, cache, relays } : { event, fetchBlob, relays });\n };\n\n return {\n async resolve(pointer: AppletPointer): Promise<AppletSummary> {\n const resolved = pointer.kind === 'builtin' ? await resolveShipped(context, pointer.id) : await lookUp(pointer);\n verified.set(keyOf(resolved.summary.identity), resolved.indexHtml);\n return resolved.summary;\n },\n install(summary: AppletSummary) {\n if (!verified.has(keyOf(summary.identity))) throw new Error('invalid:unresolved');\n context.grants.ensure(summary.identity);\n return context.installed.install(summary);\n },\n async plan(summary: AppletSummary): Promise<MountPlan> {\n const indexHtml = verified.get(keyOf(summary.identity));\n if (indexHtml === undefined) throw new Error('invalid:unresolved');\n if (context.grants.get(summary.identity)?.blocked) throw new Error('denied:blocked');\n context.grants.ensure(summary.identity);\n context.installed.install(summary);\n windowCounter += 1;\n return planMount({ summary, indexHtml, adapter: context.adapter, guardProfile: pipeline.config.profile, windowId: `applet-${windowCounter}` });\n },\n mount(plan: MountPlan, frame: FrameLike): AppletHandle {\n applyRuntimeFirewallRules(context.firewall, pipeline.config, plan.summary.identity.dTag);\n const handle = mountApplet(plan, frame, {\n bridge,\n originRegistry,\n guard: pipeline,\n onRevoked: (windowId, reason) => context.host.onRevoked(windowId, reason),\n });\n handles.set(plan.windowId, handle);\n const narrowed = context.grants.changes$.subscribe((record) => {\n const reason = grantNarrowingReason(plan, record, context.grants.baselineDomains());\n if (!reason) return;\n handle.revoked(reason);\n // As for a quarantine: removing the frame does not end kehto's session, so the binding is revoked too.\n bridge.revokeNapplet(plan.windowId, 'host');\n });\n context.subscriptions.add(narrowed);\n context.subscriptions.add(handle.status$.subscribe((status) => {\n if (status !== 'closed' && status !== 'revoked') return;\n handles.delete(plan.windowId);\n narrowed.unsubscribe();\n }));\n return handle;\n },\n applets: () => [...handles.values()],\n handleWindowMessage(event) {\n pipeline.handleWindowMessage(event, (message) => resolveWindow(handles, message), (message) => bridge.handleMessage(message));\n },\n };\n}\n","import { BehaviorSubject, map, of, Subject, Subscription, switchMap } from 'rxjs';\nimport { EventStore } from 'applesauce-core';\nimport { RelayPool } from 'applesauce-relay';\nimport type { AccountManager, IAccount } from 'applesauce-accounts';\nimport type { ISigner } from 'applesauce-signers';\nimport type { MessagingRegistry } from '@kernlize/messaging';\nimport { buildShellCapabilities, createShellBridge, type ShellAdapter, type ShellBridge } from '@kehto/shell';\nimport { createGuardConfig, describeMitigations, type GuardEvent } from '@kernlize/guard';\nimport type { AccountFileServers } from './files/file-servers.js';\nimport type { AppletIdentity, AppletSummary, Grants, GuardFacade, Kernl, KernlHost, KernlMultiplayer, KernlOptions, RelayTiers, Session } from './types.js';\nimport { createMultiplayerSettings } from './multiplayer/settings.js';\nimport { discoverToolFamilies } from './multiplayer/tool-discovery.js';\nimport { createKernlAccounts } from './applesauce/accounts.js';\nimport { isReadOnlyAccount } from './applesauce/auth-hooks.js';\nimport type { ProfileCard, Profiles } from './profiles/profiles.js';\nimport { commonActionsFor, createKernlNetwork } from './kernl-network.js';\nimport { createAppletConfig } from './applets/applet-config.js';\nimport { askUploadConsent, createBlossomUploader, type BlossomUploaderOptions } from './files/uploader.js';\nimport type { Uploader } from '@kehto/services';\nimport type { AccountMailboxes } from './relays/mailboxes.js';\nimport { createRelayTiers } from './relays/tiers.js';\nimport { SHELL_RELAY_OPTIONS } from './applesauce/relay-hooks.js';\nimport { decodePointer } from './applets/pointer.js';\nimport { defaultFetchBlob, openDefaultArtifactCache } from './applets/resolve.js';\nimport type { MountedApplet } from './applets/mount.js';\nimport { createGuardPipeline, type GuardPipeline } from './guard/pipeline.js';\nimport { applyRuntimeFirewallProfile, applyRuntimeFirewallRules, createRuntimeFirewallHooks, type RuntimeFirewallState } from './guard/runtime-rules.js';\nimport { createEnvironmentResolver, createGrants, type KernlGrants } from './grants/grants.js';\nimport { createConsentHandler, createSigningConsent, lookupReplaceable } from './consent/handler.js';\nimport { abbreviate } from './consent/describe-change.js';\nimport { createDefaultMessaging } from './messaging/default-registry.js';\nimport { messagingSigner } from './messaging/availability.js';\nimport { createPrivateMessagesBackend } from './messaging/private-backend.js';\nimport { createLegacyMessagesBackend } from './messaging/legacy-backend.js';\nimport { createRatchetMessagesBackend } from './messaging/ratchet-backend.js';\nimport { createGroupMessagesBackend } from './messaging/group-backend.js';\nimport { createDefaultBridges } from './bridges/default-registry.js';\nimport { createKernlServices, isTheme, type DirectConnectionsDeps, type KernlServiceDeps } from './kernl-services.js';\nimport { createWindowIdentities } from './multiplayer/window-identities.js';\nimport type { ApplesaucePool } from './applesauce/relay-hooks.js';\nimport { createShellAdapter } from './kernl-adapter.js';\nimport { createAppletLifecycle } from './kernl-lifecycle.js';\nimport { createKernlIntents } from './kernl-intents.js';\nimport { loadCatalog, streamCatalog } from './catalog/fetch.js';\n\n/**\n * Describe an account as a session the UI can show.\n *\n * @param account - An applesauce account.\n * @returns The session; `readOnly` when the account cannot sign.\n * @example\n * ```ts\n * toSession(ReadonlyAccount.fromPubkey(pubkey)).readOnly; // true\n * ```\n */\nexport function toSession(account: IAccount, card?: ProfileCard): Session {\n const metadata = account.metadata as { name?: unknown } | undefined;\n const named = typeof metadata?.name === 'string' ? metadata.name : account.name;\n const label = named ?? (card?.found ? card.name : abbreviate(account.pubkey));\n return { accountId: account.id, pubkey: account.pubkey, label, readOnly: isReadOnlyAccount(account) };\n}\n\ninterface ShellState {\n readonly pipeline: GuardPipeline;\n readonly firewall: RuntimeFirewallState;\n readonly bridge: ShellBridge;\n readonly handles: ReadonlyMap<string, MountedApplet>;\n readonly accounts: AccountManager;\n readonly session$: BehaviorSubject<Session | null>;\n readonly profiles: Profiles;\n readonly mailboxes: AccountMailboxes;\n readonly tiers: RelayTiers;\n}\n\n/** Keep the runtime firewall on the guard's profile and the session on the active account. */\nfunction followShellState({ pipeline, firewall, bridge, handles, accounts, session$, profiles, mailboxes, tiers }: ShellState): Subscription {\n const subscriptions = new Subscription();\n subscriptions.add(pipeline.profile$.subscribe(() => {\n applyRuntimeFirewallProfile(firewall, pipeline.config);\n for (const handle of handles.values()) applyRuntimeFirewallRules(firewall, pipeline.config, handle.summary.identity.dTag);\n }));\n subscriptions.add(accounts.active$.subscribe((account) => bridge.publishIdentityChanged(account?.pubkey ?? '')));\n // The session's label follows the account's published name once it arrives.\n const sessions = accounts.active$.pipe(switchMap((account) => (account ? profiles.card$(account.pubkey).pipe(map((card) => toSession(account, card))) : of(null))));\n subscriptions.add(sessions.subscribe(session$));\n // Where the account says it publishes is where the shell publishes for it (NIP-65, D-029).\n subscriptions.add(mailboxes.state$.subscribe((state) => {\n if (state.status === 'found') tiers.set('outbox', state.mailboxes.outboxes);\n }));\n return subscriptions;\n}\n\n/** Signing in and out. The session itself is a getter on the shell, so spreading this never copies a stale value. */\nfunction createSignIn(accounts: AccountManager): Pick<Kernl, 'login' | 'logout'> {\n return {\n async login(account) {\n if (!accounts.getAccount(account.id)) accounts.addAccount(account);\n accounts.setActive(account);\n return toSession(account);\n },\n async logout() {\n accounts.clearActive();\n },\n };\n}\n\nfunction createGuardFacade(pipeline: GuardPipeline, events$: Subject<GuardEvent>): GuardFacade {\n return {\n get config() {\n return pipeline.config;\n },\n profile$: pipeline.profile$,\n setProfile: (profile) => pipeline.setProfile(profile),\n events$: events$.asObservable(),\n mitigations: () => describeMitigations(pipeline.config),\n release: (windowId) => pipeline.release(windowId),\n };\n}\n\ninterface MessagingParts {\n readonly eventStore: EventStore;\n readonly pool: RelayPool;\n readonly tiers: RelayTiers;\n readonly accounts: AccountManager;\n}\n\n/** kernl's account-signer backends for `private`, `legacy` and `ratchet`, unless the host supplied its own. */\nfunction createAccountMessaging(options: KernlOptions, parts: MessagingParts): MessagingRegistry {\n const signer = (): ISigner | undefined => messagingSigner(parts.accounts.active);\n const deps = {\n store: parts.eventStore,\n pool: parts.pool,\n tiers: parts.tiers,\n signer,\n selfPubkey: () => parts.accounts.active?.pubkey,\n accountChanges: parts.accounts.active$,\n };\n const { host } = options;\n return createDefaultMessaging({\n storage: host.storage,\n signer,\n ...(host.chooseReply ? { askReply: host.chooseReply.bind(host) } : {}),\n backends: {\n private: () => createPrivateMessagesBackend(deps),\n legacy: () => createLegacyMessagesBackend(deps),\n ratchet: () => createRatchetMessagesBackend({ ...deps, storage: options.host.storage }),\n group: () => createGroupMessagesBackend({ ...deps, storage: options.host.storage }),\n ...options.messagingBackends,\n },\n });\n}\n\n/** The host's messaging and bridge registries, or kernl's defaults over the shell's parts. */\nfunction registriesFor(options: KernlOptions, parts: MessagingParts): Pick<Kernl, 'messaging' | 'bridges'> {\n const { host } = options;\n return {\n messaging: options.messaging ?? createAccountMessaging(options, parts),\n // host.openLink asks before leaving kernl, so every hand-off is confirmed by the user (D-010).\n bridges: options.bridges ?? createDefaultBridges({ handoff: (uri) => host.openLink(uri), ...(options.torrent ? { torrent: options.torrent } : {}) }),\n };\n}\n\ninterface MeetingParts {\n readonly pool: ApplesaucePool;\n readonly tiers: RelayTiers;\n readonly appletOf: (windowId: string) => AppletSummary | undefined;\n readonly grants: () => Grants;\n}\n\n/**\n * Remote tools and direct connections: the window keys they share, the host's settings, and the\n * person's own, with a search for tool families over the servers they chose, else the host's, else\n * the general ones (D-041, D-042, D-043).\n */\nfunction meetingFor(options: KernlOptions, parts: MeetingParts): { deps: Pick<KernlServiceDeps, 'identities' | 'remoteTools' | 'directConnections' | 'multiplayer'>; multiplayer: KernlMultiplayer } {\n const settings = createMultiplayerSettings(options.host.storage);\n const relays = (): readonly string[] => settings.state().servers ?? options.remoteTools?.relays ?? parts.tiers.get().super;\n const multiplayer = { ...settings, discover: (input: string) => discoverToolFamilies(input, { pool: parts.pool, relays: relays(), fetch: globalThis.fetch.bind(globalThis) }) };\n return {\n deps: { identities: createWindowIdentities(), remoteTools: options.remoteTools, directConnections: directConnectionsFor(options, parts.appletOf, parts.grants), multiplayer },\n multiplayer,\n };\n}\n\n/** Uploads to the account's file servers, asking the person about each file in the name of the applet that sent it (D-033). */\nfunction uploaderFor(host: KernlHost, files: AccountFileServers, signer: BlossomUploaderOptions['signer'], identityOf: (windowId: string) => AppletIdentity | undefined): Uploader {\n return createBlossomUploader({\n servers: () => files.current(),\n signer,\n ask: (windowId, details) => askUploadConsent(host, identityOf(windowId), details),\n });\n}\n\n/**\n * Direct connections, when this page can make peer connections. A session is\n * open to an applet the person granted `webrtc` and did not block, and each one\n * is put to the person through the host's consent prompt (D-042).\n */\nfunction directConnectionsFor(options: KernlOptions, appletOf: (windowId: string) => AppletSummary | undefined, grants: () => Grants): DirectConnectionsDeps | undefined {\n const { createPeer, ...settings } = options.directConnections ?? {};\n if (!createPeer && typeof RTCPeerConnection !== 'function') return undefined;\n return {\n settings,\n ...(createPeer ? { createPeer } : {}),\n appletOf,\n isGranted(windowId) {\n const identity = appletOf(windowId)?.identity;\n const record = identity && grants().get(identity);\n return !!record && !record.blocked && record.domains.includes('webrtc');\n },\n ask: (summary) => new Promise((resolve) => options.host.presentConsent({ summary, resolve })),\n };\n}\n\n/** The applet a window runs, keyed by its catalogue id so its settings outlive a version. */\nfunction appletOf(handles: ReadonlyMap<string, MountedApplet>, windowId: string): { key: string; title: string } | undefined {\n const summary = handles.get(windowId)?.summary;\n return summary && { key: summary.manifest.catalogId, title: summary.title };\n}\n\ninterface ShellParts {\n readonly handles: ReadonlyMap<string, MountedApplet>;\n readonly subscriptions: Subscription;\n readonly destroyed$: Subject<void>;\n readonly network: { readonly directory: { stop(): void }; readonly eventCache: { close(): Promise<void> } };\n readonly intents: { close(): void };\n readonly dm: { dispose(): void };\n readonly bridge: ShellBridge;\n /** Closed only when the shell created it. */\n readonly messaging?: MessagingRegistry;\n readonly pool?: RelayPool;\n}\n\n/** Close every applet, then everything the shell opened, the parts it was handed excepted. */\nfunction tearDown(parts: ShellParts): void {\n for (const handle of parts.handles.values()) handle.close();\n parts.subscriptions.unsubscribe();\n parts.destroyed$.next();\n parts.network.directory.stop();\n void parts.network.eventCache.close();\n parts.intents.close();\n parts.dm.dispose();\n parts.bridge.destroy();\n parts.messaging?.close();\n parts.pool?.close();\n}\n\n/**\n * Compose the shell: one `EventStore`, one `RelayPool`, one `AccountManager`,\n * the relay tiers, the guard pipeline, the grants layer, the messaging and\n * bridge registries, kehto's services (intents included) and\n * `createShellBridge`, the applet store's catalogue, plus the applet lifecycle\n * `decodePointer` → `resolve` → `plan` → `mount`.\n *\n * Anything the host passes in `options` is used as is; anything missing is\n * created with kernl's defaults. The host wires `handleWindowMessage` to the\n * window once and supplies the frames; everything else is reached through\n * {@link KernlHost}.\n *\n * @param options - Host hooks and optional pre-built parts.\n * @returns The shell.\n * @example\n * ```ts\n * const kernl = createKernl({ host });\n * window.addEventListener('message', (event) => kernl.handleWindowMessage(event));\n * const summary = await kernl.resolve(kernl.decodePointer(address));\n * const handle = kernl.mount(await kernl.plan(summary), iframe);\n * ```\n */\nexport function createKernl(options: KernlOptions): Kernl {\n const { host } = options;\n const ownsPool = !options.pool;\n const ownsMessaging = !options.messaging;\n const eventStore = options.eventStore ?? new EventStore();\n const pool = options.pool ?? new RelayPool(SHELL_RELAY_OPTIONS);\n const accounts = options.accounts ?? createKernlAccounts(host.storage);\n const tiers = createRelayTiers(host.storage, options.relays ?? {});\n const { messaging, bridges } = registriesFor(options, { eventStore, pool, tiers, accounts });\n\n const handles = new Map<string, MountedApplet>();\n const guardEvents$ = new Subject<GuardEvent>();\n const session$ = new BehaviorSubject<Session | null>(null);\n const destroyed$ = new Subject<void>();\n const subscriptions = new Subscription();\n let grants: KernlGrants;\n\n const pipeline = createGuardPipeline({\n config: createGuardConfig(options.guard?.profile ?? 'strict'),\n ...(host.now ? { now: host.now.bind(host) } : {}),\n onEvent: (event) => guardEvents$.next(event),\n onQuarantine: (windowId) => {\n handles.get(windowId)?.revoked('quarantine');\n bridge.revokeNapplet(windowId, 'host');\n },\n getVisibility: (windowId) => host.getVisibility(windowId),\n onRelease: (windowId) => bridge.releaseDeferred(windowId),\n });\n\n const identityOf = (windowId: string): AppletIdentity | undefined => handles.get(windowId)?.summary.identity;\n const { eventCache, replaceableLoader, profiles, directory, mailboxes, files, signer } = createKernlNetwork(options, { eventStore, pool, tiers, accounts, destroyed$ });\n const lookupBefore = lookupReplaceable(eventStore, {\n loader: replaceableLoader,\n relays: () => [...tiers.get().outbox, ...tiers.get().discovery],\n });\n const consent = createSigningConsent({ host, lookupBefore, resolveApplet: identityOf, pubkey: () => accounts.active?.pubkey });\n const meeting = meetingFor(options, { pool, tiers, appletOf: (windowId) => handles.get(windowId)?.summary, grants: () => grants });\n const services = createKernlServices({\n pool,\n tiers,\n eventStore,\n auth: { getSigner: () => adapter.auth.getSigner(), getUserPubkey: () => adapter.auth.getUserPubkey() },\n consent,\n host,\n bridges,\n messaging,\n profiles,\n ...(host.presentSettings ? { config: createAppletConfig({ storage: host.storage, appletOf: (windowId) => appletOf(handles, windowId), present: host.presentSettings.bind(host) }) } : {}),\n common: commonActionsFor({ eventStore, pool, tiers, accounts }, { profiles, replaceableLoader, signer }, consent),\n uploader: uploaderFor(host, files, signer, identityOf),\n ...(isTheme(options.theme) ? { theme: options.theme } : {}),\n ...meeting.deps,\n resolveIdentity(windowId) {\n const identity = identityOf(windowId);\n return identity ? { dTag: identity.dTag, aggregateHash: identity.hash } : null;\n },\n });\n\n const intents = createKernlIntents({ host, pool, tiers, accounts, handles, ...(options.intentRetry ? { retry: options.intentRetry } : {}) });\n services.registry.intent = intents.handler;\n const runtimeFirewall = createRuntimeFirewallHooks({\n storage: host.storage,\n onEvent: (event) => guardEvents$.next(event),\n ...(host.now ? { now: host.now.bind(host) } : {}),\n });\n const adapter: ShellAdapter = createShellAdapter({\n pool,\n tiers,\n accounts,\n consent,\n services: services.registry,\n resolveEnvironment: (identity, available) => createEnvironmentResolver(grants)(identity, available),\n onNappletRevoked: ({ windowId, reason }) => handles.get(windowId)?.revoked(reason),\n filterNappletMessage: (windowId, message) => pipeline.observe(windowId, identityOf(windowId)?.dTag ?? 'unknown', message),\n getFocusContext: (windowId) => ({ focused: pipeline.getVisibility(windowId).focused }),\n runtimeFirewall,\n });\n const bridge = createShellBridge(adapter);\n grants = createGrants({ acl: bridge.runtime.aclState, storage: host.storage, availableDomains: () => buildShellCapabilities(adapter).domains });\n bridge.registerConsentHandler(createConsentHandler(host, lookupBefore, identityOf));\n\n subscriptions.add(followShellState({ pipeline, firewall: runtimeFirewall.legacyFirewall, bridge, handles, accounts, session$, profiles, mailboxes, tiers }));\n\n const lifecycle = createAppletLifecycle({\n pool,\n tiers,\n adapter,\n bridge,\n pipeline,\n firewall: runtimeFirewall.legacyFirewall,\n grants,\n installed: intents.installed,\n host,\n handles,\n subscriptions,\n openCache: options.artifactCache ?? openDefaultArtifactCache,\n fetchBlob: host.fetchBlob ? host.fetchBlob.bind(host) : defaultFetchBlob,\n builtins: options.builtins ?? [],\n });\n\n return {\n accounts,\n eventStore,\n pool,\n bridge,\n guard: createGuardFacade(pipeline, guardEvents$),\n grants,\n relays: tiers,\n messaging,\n bridges,\n catalog: {\n load: (loadOptions) => loadCatalog(pool, tiers, { cache: eventCache.cacheRequest, store: eventStore, ...loadOptions }),\n stream: (streamOptions) => streamCatalog(pool, tiers, { cache: eventCache.cacheRequest, store: eventStore, ...streamOptions }),\n },\n profiles,\n mailboxes,\n files,\n multiplayer: meeting.multiplayer,\n directory,\n intents: intents.intents,\n session$,\n get session() {\n return session$.value;\n },\n ...createSignIn(accounts),\n decodePointer,\n ...lifecycle,\n destroy: () =>\n tearDown({ handles, subscriptions, destroyed$, network: { directory, eventCache }, intents, dm: services.dm, bridge, ...(ownsMessaging ? { messaging } : {}), ...(ownsPool ? { pool } : {}) }),\n };\n}\n","import { Subscription } from 'rxjs';\nimport type { AccountManager, IAccount } from 'applesauce-accounts';\nimport type { ServiceHandler, ServiceRuntimeContext } from '@kehto/runtime';\nimport { createIntentService } from '@kehto/services';\nimport type { EventTemplate, NostrEvent } from '@napplet/core';\nimport type { Intents, KernlHost, RelayTiers } from './types.js';\nimport type { ApplesaucePool } from './applesauce/relay-hooks.js';\nimport { isReadOnlyAccount } from './applesauce/auth-hooks.js';\nimport type { MountedApplet } from './applets/mount.js';\nimport { createHandlerDefaults, type PreferenceSigner } from './intents/defaults.js';\nimport { createIntentDelivery } from './intents/delivery.js';\nimport { createInstalledApplets, type InstalledApplets } from './intents/installed.js';\nimport { createIntentRouter } from './intents/router.js';\n\n/** What {@link createKernlIntents} needs from the composed shell. */\nexport interface KernlIntentDeps {\n readonly host: KernlHost;\n readonly pool: ApplesaucePool;\n readonly tiers: RelayTiers;\n readonly accounts: AccountManager;\n /** Live applet handles by window id; the source of every sender identity. */\n readonly handles: ReadonlyMap<string, MountedApplet>;\n readonly retry?: { readonly intervalMs: number; readonly attempts: number };\n}\n\n/** The intent service for kehto's registry, the user-facing surface and the installed set the lifecycle writes. */\nexport interface KernlIntents {\n readonly handler: ServiceHandler;\n readonly intents: Intents;\n readonly installed: InstalledApplets;\n close(): void;\n}\n\nconst FAILURES: Readonly<Record<string, string>> = {\n 'unavailable:delivery': 'It needs \"opening other applets\" switched on in its grants to receive requests from other applets.',\n 'unavailable:window': 'It could not be opened.',\n 'unavailable:handler': 'It is no longer installed.',\n};\n\n/** What the user is told when the host itself failed while opening the handler. */\nconst UNREACHABLE = 'It could not be reached.';\n\nfunction signerOf(account: IAccount | undefined): PreferenceSigner | undefined {\n if (!account || isReadOnlyAccount(account)) return undefined;\n return (template: EventTemplate) => account.signEvent(template) as Promise<NostrEvent>;\n}\n\n/**\n * Keep the runtime context kehto hands the intent service, so delivery can\n * use the runtime's recipient-checked send rather than a raw port.\n */\nfunction withContext(inner: ServiceHandler, hold: (context: ServiceRuntimeContext | undefined) => void): ServiceHandler {\n return {\n ...inner,\n onRegistered(context) {\n hold(context);\n inner.onRegistered?.(context);\n },\n onUnregistered() {\n hold(undefined);\n inner.onUnregistered?.();\n },\n };\n}\n\n/**\n * Compose NAP-INTENT for the shell: the installed set, the user's handler\n * defaults, kernl's router over kehto's catalogue resolver, delivery through\n * the host's window opener, and kehto's `createIntentService`.\n *\n * The sender of every invocation is the verified catalogue id of the window\n * it came from, looked up from the shell's own handles and never from the\n * message. The user's published preferences are re-read whenever the active\n * account changes. A delivery that fails after acceptance is reported to the\n * user, since the source has already been told yes.\n *\n * @param deps - Host, pool, tiers, accounts and live handles.\n * @returns The service handler, the facade and the installed set.\n * @example\n * ```ts\n * const intents = createKernlIntents({ host, pool, tiers, accounts, handles });\n * services.registry.intent = intents.handler;\n * ```\n */\nexport function createKernlIntents(deps: KernlIntentDeps): KernlIntents {\n const { host, handles } = deps;\n const installed = createInstalledApplets(host.storage, host.now ? host.now.bind(host) : Date.now);\n const defaults = createHandlerDefaults({\n storage: host.storage,\n pool: deps.pool,\n tiers: deps.tiers,\n pubkey: () => deps.accounts.active?.pubkey,\n signer: () => signerOf(deps.accounts.active),\n });\n let context: ServiceRuntimeContext | undefined;\n const titleOf = (catalogId: string): string => installed.get(catalogId)?.title ?? 'An applet';\n\n const deliver = createIntentDelivery({\n installed,\n findWindow: (catalogId) => [...handles.values()].find((handle) => handle.summary.manifest.catalogId === catalogId)?.windowId,\n openApplet: async (address) => host.openApplet?.(address),\n ...(host.focusApplet ? { focus: host.focusApplet.bind(host) } : {}),\n // The runtime's recipient gate maps `intent.deliver` to `intent:read` since @kehto/acl 0.20.6,\n // so delivery goes through it to a live, unblocked, granted target (DECISIONS.md D-037).\n send: (windowId, message) => context?.sendToEligibleNapplet(windowId, message) === true,\n ...(deps.retry ? { retry: deps.retry } : {}),\n });\n\n const router = createIntentRouter({\n installed,\n defaults,\n ...(host.chooseHandler ? { choose: host.chooseHandler.bind(host) } : {}),\n describeSender: titleOf,\n deliver: (params) =>\n deliver(params).catch((error: Error) => {\n host.notify({ title: `${titleOf(params.handler)} could not take the request`, body: FAILURES[error.message] ?? UNREACHABLE, tone: 'warning' });\n throw error;\n }),\n });\n\n const service = createIntentService({ resolver: router, resolveSender: (windowId) => handles.get(windowId)?.summary.manifest.catalogId });\n const subscriptions = new Subscription();\n subscriptions.add(installed.changes$.subscribe((list) => {\n for (const slug of new Set(list.flatMap((applet) => applet.contracts.map((contract) => contract.slug)))) router.notifyChanged(slug);\n }));\n subscriptions.add(defaults.changes$.subscribe((archetype) => router.notifyChanged(archetype)));\n subscriptions.add(deps.accounts.active$.subscribe(() => void defaults.load()));\n\n return {\n handler: withContext(service, (next) => {\n context = next;\n }),\n installed,\n intents: {\n installed$: installed.changes$,\n installed: () => installed.list(),\n uninstall: (catalogId) => installed.remove(catalogId),\n defaults,\n },\n close: () => subscriptions.unsubscribe(),\n };\n}\n","import { lastValueFrom, Subject, takeUntil, timer, toArray, type Observable } from 'rxjs';\nimport { verifyEvent } from 'applesauce-core/helpers';\nimport type { EventTemplate, NostrEvent } from '@napplet/core';\nimport type { RelayTiers, StorageLike } from '../types.js';\nimport { asFilters, type ApplesaucePool } from '../applesauce/relay-hooks.js';\nimport { createNamespacedStore } from '../persistence/store.js';\nimport { HANDLER_PREFERENCES_KIND, parseHandlerPreferences, preferenceTemplate, type HandlerPreferences } from './preferences.js';\n\n/** Signs the shell's own preference events. Present only while the active account can sign. */\nexport type PreferenceSigner = (template: EventTemplate) => Promise<NostrEvent>;\n\n/** What {@link createHandlerDefaults} needs. */\nexport interface HandlerDefaultsOptions {\n readonly storage: StorageLike;\n readonly pool: ApplesaucePool;\n readonly tiers: RelayTiers;\n /** The signed-in account's public key, if any. */\n readonly pubkey: () => string | undefined;\n readonly signer: () => PreferenceSigner | undefined;\n /** Seconds since the epoch. */\n readonly now?: () => number;\n}\n\n/** The user's handler choices: what this device remembers, and what their account published. */\nexport interface HandlerDefaults {\n /** This device's default for an archetype. */\n get(archetype: string): string | undefined;\n /** Every default this device remembers, by archetype. */\n all(): Readonly<Record<string, string>>;\n /**\n * Remember a default, or forget it with `undefined`. With `sync` on and an\n * account that can sign, the choice is also published as the user's\n * handler preference for the archetype.\n */\n set(archetype: string, catalogId: string | undefined): Promise<void>;\n /** The account's published preferences for an archetype, once loaded. */\n synced(archetype: string): HandlerPreferences | undefined;\n /** Read the signed-in account's published preferences from its relays. */\n load(): Promise<void>;\n /** Whether choices are published to the account. Off until the user turns it on. */\n readonly sync: boolean;\n setSync(on: boolean): void;\n /** The archetype whose defaults or published preferences just changed. */\n readonly changes$: Observable<string>;\n}\n\nconst DEFAULTS_KEY = 'intent-defaults:v1';\n/** Published preferences that have not arrived after this long are read on the next sign-in. */\nconst LOAD_TIMEOUT_MS = 8000;\nconst SYNC_KEY = 'intent-sync:v1';\n\n/**\n * The relays a preference event is read from and written to: the user's\n * outbox, then the public relays (the spec's NIP-65 write relays, as the shell\n * knows them).\n *\n * @param tiers - The shell's relay tiers.\n * @returns Deduplicated relay URLs.\n * @example\n * ```ts\n * preferenceRelays(tiers); // ['wss://relay.mine', 'wss://relay.damus.io', …]\n * ```\n */\nexport function preferenceRelays(tiers: RelayTiers): readonly string[] {\n const { outbox, super: shared } = tiers.get();\n return [...new Set([...outbox, ...shared])];\n}\n\nfunction newestPerArchetype(events: readonly NostrEvent[], pubkey: string): Map<string, NostrEvent> {\n const newest = new Map<string, NostrEvent>();\n for (const event of events) {\n // The spec's rule: apply only events whose signature verifies and whose author is the user.\n if (event.kind !== HANDLER_PREFERENCES_KIND || event.pubkey !== pubkey || !verifyEvent(event)) continue;\n const archetype = event.tags.find((tag) => tag[0] === 'd')?.[1] ?? '';\n const current = newest.get(archetype);\n if (archetype && (!current || event.created_at > current.created_at)) newest.set(archetype, event);\n }\n return newest;\n}\n\n/**\n * Handler defaults over local storage and the account's kind-31129 events.\n *\n * Local defaults are kept at `kernl:intent-defaults:v1` and always win, as the\n * spec allows a shell's own preferences to select without prompting. Published\n * preferences are read for the signed-in account and used to rank and\n * pre-select handlers. Publishing is opt-in (`kernl:intent-sync:v1`), because\n * the archetype a user set preferences for is public.\n *\n * @param options - Storage, pool, tiers and the active account's key and signer.\n * @returns The defaults.\n * @example\n * ```ts\n * const defaults = createHandlerDefaults({ storage, pool, tiers, pubkey, signer });\n * await defaults.set('profile', 'nip5d:35129:…:profile-viewer');\n * ```\n */\nexport function createHandlerDefaults(options: HandlerDefaultsOptions): HandlerDefaults {\n const store = createNamespacedStore(options.storage, 'kernl');\n const local = new Map(Object.entries(store.getJson<Record<string, string>>(DEFAULTS_KEY, {})));\n const published = new Map<string, NostrEvent>();\n const changes$ = new Subject<string>();\n const now = options.now ?? (() => Math.floor(Date.now() / 1000));\n let sync = store.getJson<boolean>(SYNC_KEY, false) === true;\n let loadedFor: string | undefined;\n\n async function publish(archetype: string, catalogId: string): Promise<void> {\n const sign = options.signer();\n const template = preferenceTemplate(published.get(archetype), archetype, catalogId, now());\n if (!sign || !template) return;\n const event = await sign(template);\n published.set(archetype, event);\n await options.pool.publish([...preferenceRelays(options.tiers)], event).catch(() => undefined);\n }\n\n return {\n get: (archetype) => local.get(archetype),\n all: () => Object.freeze(Object.fromEntries(local)),\n async set(archetype, catalogId) {\n if (catalogId === undefined) local.delete(archetype);\n else local.set(archetype, catalogId);\n store.setJson(DEFAULTS_KEY, Object.fromEntries(local));\n changes$.next(archetype);\n if (sync && catalogId !== undefined) await publish(archetype, catalogId);\n },\n synced: (archetype) => {\n const event = published.get(archetype);\n return event ? parseHandlerPreferences(event) : undefined;\n },\n async load() {\n const pubkey = options.pubkey();\n if (pubkey !== loadedFor) published.clear();\n loadedFor = pubkey;\n if (!pubkey) return;\n const request = options.pool.request([...preferenceRelays(options.tiers)], asFilters([{ kinds: [HANDLER_PREFERENCES_KIND], authors: [pubkey] }]));\n const events = await lastValueFrom(request.pipe(takeUntil(timer(LOAD_TIMEOUT_MS)), toArray()), { defaultValue: [] }).catch(() => []);\n for (const [archetype, event] of newestPerArchetype(events, pubkey)) {\n published.set(archetype, event);\n changes$.next(archetype);\n }\n },\n get sync() {\n return sync;\n },\n setSync(on) {\n sync = on;\n store.setJson(SYNC_KEY, on);\n },\n changes$: changes$.asObservable(),\n };\n}\n","import type { EventTemplate, NostrEvent } from '@napplet/core';\n\n/**\n * The addressable kind that records a user's preferred handlers, one event\n * per archetype (\"Napplet Handler Preferences\", kind 31129).\n *\n * @example\n * ```ts\n * pool.request(relays, [{ kinds: [HANDLER_PREFERENCES_KIND], authors: [pubkey] }]);\n * ```\n */\nexport const HANDLER_PREFERENCES_KIND = 31129;\n\n/** The public entries of one kind-31129 event. Private entries in `content` are kept, not read. */\nexport interface HandlerPreferences {\n readonly archetype: string;\n /** Archetype-wide `a` and `e` references, in tag order. */\n readonly handlers: readonly string[];\n /** Intent-specific `i` references by convention identity, in tag order. */\n readonly intents: Readonly<Record<string, readonly string[]>>;\n}\n\nconst HEX_64 = /^[0-9a-f]{64}$/;\nconst NAMED = /^35129:([0-9a-f]{64}):(.+)$/s;\nconst ROOT = /^15129:([0-9a-f]{64}):$/;\nconst CONVENTION = /^napplet:([a-z0-9][a-z0-9-]*)\\/([a-z0-9][a-z0-9-]*)$/;\n\n/**\n * kehto's catalogue id for a preference reference: a named or root\n * coordinate, or a snapshot id. kehto keys named applets by publisher, kind\n * and `d`, roots by publisher and kind, snapshots by event id.\n *\n * @param ref - `35129:<pubkey>:<d>`, `15129:<pubkey>:` or a 64-hex snapshot id.\n * @returns The catalogue id, or undefined for anything else.\n * @example\n * ```ts\n * catalogIdForRef(`35129:${pubkey}:notepad`); // `nip5d:35129:${pubkey}:notepad`\n * ```\n */\nexport function catalogIdForRef(ref: string): string | undefined {\n if (HEX_64.test(ref)) return `nip5d:5129:${ref}`;\n const named = NAMED.exec(ref);\n if (named) return `nip5d:35129:${named[1] as string}:${named[2] as string}`;\n const root = ROOT.exec(ref);\n return root ? `nip5d:15129:${root[1] as string}` : undefined;\n}\n\n/**\n * The preference reference for a catalogue id; the inverse of {@link catalogIdForRef}.\n *\n * @param catalogId - A kehto catalogue id.\n * @returns The coordinate or snapshot id, or undefined when the id is not a napplet's.\n * @example\n * ```ts\n * refForCatalogId(`nip5d:15129:${pubkey}`); // `15129:${pubkey}:`\n * ```\n */\nexport function refForCatalogId(catalogId: string): string | undefined {\n const [prefix, kind, first = '', ...rest] = catalogId.split(':');\n if (prefix !== 'nip5d') return undefined;\n if (kind === '5129' && HEX_64.test(first)) return first;\n if (kind === '15129' && HEX_64.test(first) && rest.length === 0) return `15129:${first}:`;\n return kind === '35129' && HEX_64.test(first) && rest.length > 0 ? `35129:${first}:${rest.join(':')}` : undefined;\n}\n\nfunction tagRef(tag: readonly string[]): string | undefined {\n const value = tag[1];\n if (typeof value !== 'string') return undefined;\n if (tag[0] === 'a') return NAMED.test(value) || ROOT.test(value) ? value : undefined;\n return tag[0] === 'e' && HEX_64.test(value) ? value : undefined;\n}\n\nfunction intentEntry(tag: readonly string[], archetype: string): readonly [string, string] | undefined {\n const [, convention, ref] = tag;\n if (tag[0] !== 'i' || typeof convention !== 'string' || typeof ref !== 'string') return undefined;\n if (CONVENTION.exec(convention)?.[1] !== archetype) return undefined;\n return catalogIdForRef(ref) ? [convention, ref] : undefined;\n}\n\n/**\n * Read the public entries of a handler-preferences event.\n *\n * Unknown tags and malformed entries are ignored without discarding the\n * event. An `i` entry counts only when its convention is queryless,\n * fragment-free and names the event's archetype.\n *\n * @param event - A kind-31129 event, already verified as the user's.\n * @returns The preferences, or undefined when the event is not one.\n * @example\n * ```ts\n * parseHandlerPreferences(event)?.handlers; // ['35129:…:notepad']\n * ```\n */\nexport function parseHandlerPreferences(event: NostrEvent): HandlerPreferences | undefined {\n const archetype = event.tags.find((tag) => tag[0] === 'd')?.[1];\n if (event.kind !== HANDLER_PREFERENCES_KIND || !archetype) return undefined;\n const handlers: string[] = [];\n const intents: Record<string, string[]> = {};\n for (const tag of event.tags) {\n const ref = tagRef(tag);\n if (ref && !handlers.includes(ref)) handlers.push(ref);\n const entry = intentEntry(tag, archetype);\n if (entry) (intents[entry[0]] ??= []).push(entry[1]);\n }\n return Object.freeze({ archetype, handlers: Object.freeze(handlers), intents: Object.freeze(intents) });\n}\n\n/**\n * Catalogue ids the user prefers for one convention: intent-specific entries\n * when any match, otherwise the archetype-wide ones.\n *\n * @param preferences - The user's preferences for the convention's archetype.\n * @param convention - The requested convention identity.\n * @returns Catalogue ids in preference order.\n * @example\n * ```ts\n * preferredHandlers(preferences, 'napplet:profile/edit'); // ['nip5d:35129:…:profile-editor']\n * ```\n */\nexport function preferredHandlers(preferences: HandlerPreferences | undefined, convention: string): readonly string[] {\n if (!preferences) return [];\n const specific = preferences.intents[convention] ?? [];\n const refs = specific.length > 0 ? specific : preferences.handlers;\n return refs.map(catalogIdForRef).filter((id): id is string => id !== undefined);\n}\n\n/**\n * The next version of the user's preferences for an archetype, with one\n * handler moved to the front of the archetype-wide entries.\n *\n * Every other tag and the encrypted private entries are carried over as they\n * were, so the shell never drops a choice it could not read.\n *\n * @param previous - The current event, when there is one.\n * @param archetype - The archetype slug.\n * @param catalogId - The handler the user chose.\n * @param now - Seconds since the epoch.\n * @returns The event to sign, or undefined when the id has no reference form.\n * @example\n * ```ts\n * preferenceTemplate(current, 'profile', candidate.id, Math.floor(Date.now() / 1000));\n * ```\n */\nexport function preferenceTemplate(previous: NostrEvent | undefined, archetype: string, catalogId: string, now: number): EventTemplate | undefined {\n const ref = refForCatalogId(catalogId);\n if (!ref) return undefined;\n const kept = (previous?.tags ?? []).filter((tag) => tag[0] !== 'd' && tag[1] !== ref);\n const tag = HEX_64.test(ref) ? ['e', ref] : ['a', ref];\n return { kind: HANDLER_PREFERENCES_KIND, created_at: now, content: previous?.content ?? '', tags: [['d', archetype], tag, ...kept] };\n}\n","import type { IntentDelivery, IntentDispatchParams } from '@kehto/services';\nimport type { NappletMessage } from '@napplet/core';\nimport type { InstalledApplets } from './installed.js';\n\n/**\n * How often, and how many times, delivery is retried while the target's\n * session comes up: 100 ms apart for up to 15 s.\n *\n * @example\n * ```ts\n * createIntentDelivery({ ...deps, retry: DELIVERY_RETRY });\n * ```\n */\nexport const DELIVERY_RETRY = Object.freeze({ intervalMs: 100, attempts: 150 });\n\n/** What {@link createIntentDelivery} needs from the shell. */\nexport interface IntentDeliveryOptions {\n readonly installed: InstalledApplets;\n /** A window already running this catalogue id, for reuse. */\n readonly findWindow: (catalogId: string) => string | undefined;\n /** Ask the host to open the applet at this address; resolves to its window id, or undefined when it did not open. */\n readonly openApplet: (address: string) => Promise<string | undefined>;\n readonly focus?: (windowId: string) => void;\n /** The runtime's recipient-checked send; false while the target is not eligible yet. */\n readonly send: (windowId: string, message: NappletMessage) => boolean;\n readonly retry?: { readonly intervalMs: number; readonly attempts: number };\n}\n\nconst pause = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));\n\n/**\n * Deliver an accepted intent to its target.\n *\n * A running window of the handler is reused unless the request said\n * `reuse: false`, and focused unless it said `focus: false`; otherwise the\n * host opens the applet. The delivery is retried until the target's session\n * is live and holds the `intent` domain, because the runtime delivers only to\n * an eligible recipient (NAP-INTENT: \"deliver only after the target is\n * ready\"). The source window plays no part after acceptance.\n *\n * @param options - Installed set, window lookup, opener, focus and the runtime send.\n * @returns The target controller's delivery function.\n * @throws `unavailable:handler` when the handler is no longer installed, `unavailable:window` when it did not open, `unavailable:delivery` when it never became eligible.\n * @example\n * ```ts\n * const deliver = createIntentDelivery({ installed, findWindow, openApplet: host.openApplet, send });\n * await deliver(params);\n * ```\n */\nexport function createIntentDelivery(options: IntentDeliveryOptions): (params: IntentDispatchParams) => Promise<void> {\n const retry = options.retry ?? DELIVERY_RETRY;\n return async (params) => {\n const applet = options.installed.get(params.handler);\n if (!applet) throw new Error('unavailable:handler');\n const running = params.behavior?.reuse === false ? undefined : options.findWindow(params.handler);\n if (running && params.behavior?.focus !== false) options.focus?.(running);\n const windowId = running ?? (await options.openApplet(applet.address));\n if (!windowId) throw new Error('unavailable:window');\n const delivery: IntentDelivery = {\n sender: params.sender,\n archetype: params.archetype,\n action: params.action,\n convention: params.convention,\n ...(params.payload === undefined ? {} : { payload: params.payload }),\n };\n for (let attempt = 0; attempt < retry.attempts; attempt += 1) {\n if (options.send(windowId, { type: 'intent.deliver', delivery } as NappletMessage)) return;\n await pause(retry.intervalMs);\n }\n throw new Error('unavailable:delivery');\n };\n}\n","import { BehaviorSubject, type Observable } from 'rxjs';\nimport { manifestToIntentCatalogEntry, type IntentCatalogEntry } from '@kehto/services';\nimport type { AppletSummary, StorageLike } from '../types.js';\nimport { createNamespacedStore } from '../persistence/store.js';\n\n/** One advertised convention, as the verified manifest's `z` and `i` tags declared it. */\nexport interface InstalledContract {\n readonly slug: string;\n readonly convention: string;\n readonly params: readonly string[];\n}\n\n/** An applet the user has run, remembered so other applets can hand work to it. */\nexport interface InstalledApplet {\n readonly catalogId: string;\n /** What the shell resolves to open it again. */\n readonly address: string;\n readonly title: string;\n readonly publisher: string;\n readonly contracts: readonly InstalledContract[];\n readonly installedAt: number;\n}\n\n/** What installing reads from a verified applet's summary. */\nexport type InstallableApplet = Pick<AppletSummary, 'address' | 'title' | 'publisher'> & {\n readonly manifest: Pick<AppletSummary['manifest'], 'catalogId' | 'archetypes'>;\n};\n\n/** The installed set: what NAP-INTENT's `available()` and `handlers()` are built from. */\nexport interface InstalledApplets {\n list(): readonly InstalledApplet[];\n get(catalogId: string): InstalledApplet | undefined;\n /** Remember a verified applet. Re-installing replaces its contracts and keeps its place. */\n install(summary: InstallableApplet): InstalledApplet;\n remove(catalogId: string): void;\n /** The installed set as kehto's catalogue resolver reads it. */\n catalog(): readonly IntentCatalogEntry[];\n /** Replays the current list to new subscribers. */\n readonly changes$: Observable<readonly InstalledApplet[]>;\n}\n\nconst STORAGE_KEY = 'installed:v1';\n\nfunction isInstalled(value: unknown): value is InstalledApplet {\n if (typeof value !== 'object' || value === null) return false;\n const row = value as Record<string, unknown>;\n return typeof row.catalogId === 'string' && typeof row.address === 'string' && typeof row.title === 'string' && typeof row.publisher === 'string' && Array.isArray(row.contracts) && typeof row.installedAt === 'number';\n}\n\n/** A contract kehto's adapter refuses is dropped, never fatal: an odd `i` tag must not hide the applet. */\nfunction toCatalogEntry(applet: InstalledApplet): IntentCatalogEntry | undefined {\n const archetypes = applet.contracts.filter((contract) => {\n try {\n manifestToIntentCatalogEntry({ catalogId: applet.catalogId, archetypes: [{ ...contract, params: [...contract.params] }] });\n return true;\n } catch {\n return false;\n }\n });\n if (archetypes.length === 0) return undefined;\n return manifestToIntentCatalogEntry({ catalogId: applet.catalogId, title: applet.title, archetypes: archetypes.map((contract) => ({ ...contract, params: [...contract.params] })) });\n}\n\n/**\n * The applets the user has run, persisted at `kernl:installed:v1`.\n *\n * Installing happens when the shell plans a verified applet, so the routing\n * contracts always come from a verified manifest (NAP-INTENT, \"Runtime\n * Behavior\"). Advertisements are routing hints; they grant nothing.\n *\n * @param storage - Where the list is kept.\n * @param now - Clock for `installedAt`.\n * @returns The installed set.\n * @example\n * ```ts\n * const installed = createInstalledApplets(localStorage);\n * installed.install(summary);\n * installed.catalog(); // [{ id: 'nip5d:35129:…:notepad', archetypes: { 'text-editor': … } }]\n * ```\n */\nexport function createInstalledApplets(storage: StorageLike, now: () => number = Date.now): InstalledApplets {\n const store = createNamespacedStore(storage, 'kernl');\n const stored = store.getJson<unknown>(STORAGE_KEY, []);\n const changes$ = new BehaviorSubject<readonly InstalledApplet[]>(Object.freeze(Array.isArray(stored) ? stored.filter(isInstalled) : []));\n\n const commit = (next: readonly InstalledApplet[]): void => {\n store.setJson(STORAGE_KEY, next);\n changes$.next(Object.freeze([...next]));\n };\n\n return {\n list: () => changes$.value,\n get: (catalogId) => changes$.value.find((applet) => applet.catalogId === catalogId),\n install(summary) {\n const { manifest } = summary;\n const previous = changes$.value.find((applet) => applet.catalogId === manifest.catalogId);\n const applet: InstalledApplet = Object.freeze({\n catalogId: manifest.catalogId,\n address: summary.address,\n title: summary.title,\n publisher: summary.publisher,\n contracts: Object.freeze(manifest.archetypes.map((entry) => Object.freeze({ slug: entry.slug, convention: entry.convention, params: Object.freeze([...entry.params]) }))),\n installedAt: previous?.installedAt ?? now(),\n });\n commit(previous ? changes$.value.map((entry) => (entry === previous ? applet : entry)) : [...changes$.value, applet]);\n return applet;\n },\n remove(catalogId) {\n if (changes$.value.some((applet) => applet.catalogId === catalogId)) commit(changes$.value.filter((applet) => applet.catalogId !== catalogId));\n },\n catalog: () => changes$.value.map(toCatalogEntry).filter((entry): entry is IntentCatalogEntry => entry !== undefined),\n changes$: changes$.asObservable(),\n };\n}\n","import { createCatalogIntentResolver, type IntentCandidate, type IntentDispatchParams, type IntentRequest, type IntentResolver, type IntentResult } from '@kehto/services';\nimport type { HandlerChoice, HandlerOption, HandlerPrompt } from '../types.js';\nimport type { HandlerDefaults } from './defaults.js';\nimport type { InstalledApplet, InstalledApplets } from './installed.js';\nimport { catalogIdForRef, preferredHandlers } from './preferences.js';\n\n/** What {@link createIntentRouter} needs. */\nexport interface IntentRouterOptions {\n readonly installed: InstalledApplets;\n readonly defaults: HandlerDefaults;\n /** Ask the user to pick a handler; absent in hosts with no chooser. */\n readonly choose?: (prompt: HandlerPrompt) => Promise<HandlerChoice | undefined>;\n /** A plain name for the applet that asked, from its runtime-attested catalogue id. */\n readonly describeSender: (sender: string) => string;\n /** Start or reuse the target and deliver; the promise settles when delivery succeeded or failed for good. */\n readonly deliver: (params: IntentDispatchParams) => Promise<void>;\n}\n\n/** kehto's resolver plus the shell's change notifications. */\nexport interface IntentRouter extends IntentResolver {\n notifyChanged(archetype: string): void;\n}\n\n/** Failures the shell answers by offering to find a handler in the store. */\nconst NO_HANDLER: ReadonlySet<string> = new Set(['no handler', 'unsupported convention', 'unsupported action']);\n\nconst isExplicit = (handler: string | undefined): boolean => handler !== undefined && handler !== 'default' && handler !== 'choose';\n\n/**\n * kernl's NAP-INTENT routing over kehto's `createCatalogIntentResolver`.\n *\n * kehto applies the spec's precedence and exact convention matching; kernl\n * supplies the installed catalogue, the user's defaults, the chooser and\n * delivery. The user's published preferences rank the chooser and pre-select a\n * handler when exactly one compatible preferred handler is installed. When no\n * installed applet can take the request, the user is asked once to pick one\n * from the store; a handler picked that way is used for this request only\n * through a one-time explicit authorisation, so an applet can never address a\n * handler the user did not choose (NAP-INTENT, \"Runtime Behavior\").\n *\n * @param options - Installed set, defaults, chooser, sender names and delivery.\n * @returns The resolver for kehto's intent service.\n * @example\n * ```ts\n * const router = createIntentRouter({ installed, defaults, choose, describeSender, deliver });\n * createIntentService({ resolver: router, resolveSender });\n * ```\n */\nexport function createIntentRouter(options: IntentRouterOptions): IntentRouter {\n const { installed, defaults } = options;\n const pending = new Map<string, IntentRequest>();\n const rerouted = new Map<string, string>();\n const authorised = new Set<string>();\n const pairKey = (sender: string, handler: string): string => `${sender}\\n${handler}`;\n\n async function ask(request: IntentRequest, candidates: readonly IntentCandidate[], sender: string): Promise<HandlerChoice | undefined> {\n if (!options.choose) return undefined;\n const preferred = preferredHandlers(defaults.synced(request.archetype), request.convention);\n const rank = (id: string): number => (preferred.includes(id) ? preferred.indexOf(id) : preferred.length);\n const choices: HandlerOption[] = candidates\n .map((candidate) => {\n // Candidates come from the installed catalogue, so each one is installed.\n const applet = installed.get(candidate.id) as InstalledApplet;\n return { id: candidate.id, title: applet.title, address: applet.address, preferred: preferred.includes(candidate.id) };\n })\n .sort((a, b) => rank(a.id) - rank(b.id));\n const hint = request.handlerHint?.address;\n const choice = await options.choose({\n archetype: request.archetype,\n action: request.action,\n convention: request.convention,\n source: options.describeSender(sender),\n options: choices,\n ...(hint ? { recommended: hint } : {}),\n });\n if (choice?.remember) await defaults.set(request.archetype, choice.id).catch(() => undefined);\n return choice;\n }\n\n async function chooseHandler(archetype: string, candidates: readonly IntentCandidate[], sender: string): Promise<string | undefined> {\n // kehto calls this only from inside `invoke`, which recorded the request for this sender.\n const request = pending.get(sender) as IntentRequest;\n const preferred = preferredHandlers(defaults.synced(archetype), request.convention).filter((id) => candidates.some((candidate) => candidate.id === id));\n if (preferred.length === 1 && request.handler !== 'choose') return preferred[0];\n const choice = await ask(request, candidates, sender);\n if (choice && !candidates.some((candidate) => candidate.id === choice.id)) {\n rerouted.set(sender, choice.id);\n return undefined;\n }\n return choice?.id;\n }\n\n const resolver = createCatalogIntentResolver({\n loadCatalog: () => installed.catalog(),\n targets: { accept: (params) => ({ completion: options.deliver(params) }) },\n getDefaultHandler: (archetype) => {\n const id = defaults.get(archetype);\n return id && installed.get(id) ? id : undefined;\n },\n // Without a chooser kehto refuses an undecided request as \"invoke rejected\"; with one, a dismissal is \"user cancelled\".\n ...(options.choose ? { chooseHandler } : {}),\n authorizeExplicitHandler: (sender, handler) => authorised.delete(pairKey(sender, handler)),\n resolveHandlerHint: (hint, candidates) => candidates.find((candidate) => candidate.id === catalogIdForRef(hint.address))?.id,\n });\n\n async function rerouteFor(request: IntentRequest, result: Extract<IntentResult, { ok: false }>, sender: string): Promise<string | undefined> {\n const picked = rerouted.get(sender);\n rerouted.delete(sender);\n if (picked) return picked;\n if (!NO_HANDLER.has(result.error) || isExplicit(request.handler)) return undefined;\n return (await ask(request, [], sender))?.id;\n }\n\n return {\n async invoke(request, context) {\n pending.set(context.sender, request);\n let handler: string | undefined;\n try {\n const result = await resolver.invoke(request, context);\n if (result.ok) return result;\n handler = await rerouteFor(request, result, context.sender);\n if (!handler || !installed.get(handler)) return result;\n authorised.add(pairKey(context.sender, handler));\n return await resolver.invoke({ ...request, handler }, context);\n } finally {\n pending.delete(context.sender);\n if (handler) authorised.delete(pairKey(context.sender, handler));\n }\n },\n available: (archetype) => resolver.available(archetype),\n handlers: () => resolver.handlers(),\n // kehto's catalogue resolver always implements it; the interface marks it optional for other resolvers.\n onChanged: resolver.onChanged as NonNullable<IntentResolver['onChanged']>,\n notifyChanged: (archetype) => resolver.notifyChanged(archetype),\n };\n}\n","import { auditTime, catchError, EMPTY, from, lastValueFrom, map, merge, mergeAll, type Observable, scan, share, takeUntil, tap, timer } from 'rxjs';\nimport { getSeenRelays, type Filter } from 'applesauce-core/helpers';\nimport { NAPPLET_KIND_NAMED, NAPPLET_KIND_ROOT } from '@kehto/nip/5d';\nimport type { NostrEvent, NostrFilter } from '@napplet/core';\nimport type { RelayTiers } from '../types.js';\nimport { asFilters, type ApplesaucePool } from '../applesauce/relay-hooks.js';\nimport { newestEntries, toCatalogEntry, type CatalogEntry } from './entry.js';\nimport { DELETION_KIND, isWithdrawn, withdraw, type Withdrawals } from './withdrawn.js';\n\n/**\n * How many manifests the store asks each relay for.\n *\n * @example\n * ```ts\n * await loadCatalog(pool, tiers, { limit: CATALOG_LIMIT });\n * ```\n */\nexport const CATALOG_LIMIT = 500;\n\n/**\n * The longest the store keeps asking a relay that has not finished. Entries are\n * listed as they arrive, so this is the outer bound, not a wait (D-028).\n *\n * @example\n * ```ts\n * await loadCatalog(pool, tiers, { timeoutMs: CATALOG_TIMEOUT_MS }); // at most 30 s\n * ```\n */\nexport const CATALOG_TIMEOUT_MS = 30_000;\n\n/**\n * When nothing has arrived after this long, the stream says so with an empty\n * list and keeps listening; it is a moment to tell the person, not a cut-off.\n *\n * @example\n * ```ts\n * streamCatalog(pool, tiers, { settleMs: CATALOG_SETTLE_MS });\n * ```\n */\nexport const CATALOG_SETTLE_MS = 3000;\n\n/**\n * How often, at most, the streamed catalogue emits while manifests pour in.\n *\n * @example\n * ```ts\n * streamCatalog(pool, tiers); // emits at most every CATALOG_EMIT_MS\n * ```\n */\nexport const CATALOG_EMIT_MS = 120;\n\n/** Options for {@link loadCatalog}. */\nexport interface LoadCatalogOptions {\n /** Per-relay manifest limit; {@link CATALOG_LIMIT} by default. */\n readonly limit?: number;\n /** Only manifests from these publishers. */\n readonly publishers?: readonly string[];\n /** The outer bound on a relay that never finishes; {@link CATALOG_TIMEOUT_MS} by default. */\n readonly timeoutMs?: number;\n /** How often the stream emits at most; {@link CATALOG_EMIT_MS} by default. */\n readonly emitMs?: number;\n /** When an empty list is emitted if nothing has arrived; {@link CATALOG_SETTLE_MS} by default. */\n readonly settleMs?: number;\n /** Manifests seen before, listed at once while the relays are asked for newer ones. */\n readonly cache?: (filters: Filter[]) => Promise<NostrEvent[]>;\n /** Where manifests from the relays are kept, so the event cache holds them for the next visit. */\n readonly store?: { add(event: NostrEvent): unknown };\n}\n\n/**\n * The relays the store reads: the applet catalogue tier first, then the\n * public relays most publishers also write to.\n *\n * @param tiers - The shell's relay tiers.\n * @returns Deduplicated relay URLs.\n * @example\n * ```ts\n * catalogRelays(tiers); // ['wss://relay.napplet.soy', 'wss://relay.damus.io', …]\n * ```\n */\nexport function catalogRelays(tiers: RelayTiers): readonly string[] {\n const { apps, super: shared } = tiers.get();\n return Object.freeze([...new Set([...apps, ...shared])]);\n}\n\nfunction catalogFilters(options: LoadCatalogOptions): NostrFilter[] {\n const limit = options.limit ?? CATALOG_LIMIT;\n const authors = options.publishers ? { authors: [...options.publishers] } : {};\n return [\n { kinds: [NAPPLET_KIND_NAMED, NAPPLET_KIND_ROOT], limit, ...authors },\n { kinds: [DELETION_KIND], '#k': [String(NAPPLET_KIND_NAMED), String(NAPPLET_KIND_ROOT)], limit, ...authors },\n ];\n}\n\ninterface Found {\n readonly listed: readonly { readonly event: NostrEvent; readonly entry: CatalogEntry }[];\n readonly withdrawn: Withdrawals;\n}\n\nfunction hintsFor(event: NostrEvent, relays: readonly string[]): readonly string[] {\n const seen = [...(getSeenRelays(event) ?? [])];\n return seen.length > 0 ? seen.slice(0, 2) : relays.slice(0, 2);\n}\n\n/**\n * Stream the applets published to the store's relays.\n *\n * Root and named manifests are fetched; pinned versions are reached by\n * pasting their address. A manifest its publisher deleted (NIP-09) is not\n * listed, even when a relay still serves it. The list is emitted again as manifests arrive, so\n * the first relay to answer fills the store while slower ones are still\n * talking. A relay that fails contributes nothing and never discards what\n * others sent; when nothing has arrived after `settleMs` an empty list says\n * so, and listening goes on. The stream completes when every relay has\n * finished, or at the outer bound.\n *\n * @param pool - The shared applesauce pool.\n * @param tiers - The shell's relay tiers.\n * @param options - Limit, publisher filter and outer bound.\n * @returns The growing list, one entry per applet, newest first.\n * @example\n * ```ts\n * streamCatalog(pool, tiers).subscribe((entries) => render(searchCatalog(entries, { text: 'notes' })));\n * ```\n */\nexport function streamCatalog(pool: ApplesaucePool, tiers: RelayTiers, options: LoadCatalogOptions = {}): Observable<readonly CatalogEntry[]> {\n const relays = catalogRelays(tiers);\n const filters = asFilters(catalogFilters(options));\n const cached = options.cache ? from(options.cache(filters).catch(() => [])).pipe(mergeAll()) : EMPTY;\n const live = pool.request([...relays], filters).pipe(\n takeUntil(timer(options.timeoutMs ?? CATALOG_TIMEOUT_MS)),\n catchError(() => EMPTY),\n tap((event) => options.store?.add(event)),\n );\n const events = merge(cached, live);\n const found = events.pipe(\n scan((state: Found, event): Found => {\n if (event.kind === DELETION_KIND) return { ...state, withdrawn: withdraw(state.withdrawn, event) };\n const entry = toCatalogEntry(event, hintsFor(event, relays));\n return entry ? { ...state, listed: [...state.listed, { event, entry }] } : state;\n }, { listed: [], withdrawn: new Map() }),\n );\n const listed = (state: Found): readonly CatalogEntry[] => newestEntries(state.listed.filter(({ event }) => !isWithdrawn(event, state.withdrawn)).map(({ entry }) => entry));\n const lists = found.pipe(auditTime(options.emitMs ?? CATALOG_EMIT_MS), map(listed), share());\n const nothingYet = timer(options.settleMs ?? CATALOG_SETTLE_MS).pipe(map((): readonly CatalogEntry[] => Object.freeze([])), takeUntil(lists));\n return merge(nothingYet, lists);\n}\n\n/**\n * List the applets published to the store's relays, once every relay has\n * finished or the outer bound passed. Prefer {@link streamCatalog} for UI.\n *\n * @param pool - The shared applesauce pool.\n * @param tiers - The shell's relay tiers.\n * @param options - Limit and publisher filter.\n * @returns One entry per applet, newest first.\n * @example\n * ```ts\n * const entries = await loadCatalog(pool, tiers);\n * searchCatalog(entries, { text: 'notes' });\n * ```\n */\nexport async function loadCatalog(pool: ApplesaucePool, tiers: RelayTiers, options: LoadCatalogOptions = {}): Promise<readonly CatalogEntry[]> {\n return lastValueFrom(streamCatalog(pool, tiers, options), { defaultValue: Object.freeze([]) });\n}\n","import type { NostrEvent } from '@napplet/core';\n\n/** Deletion requests (NIP-09). */\nexport const DELETION_KIND = 5;\n\n/** What a publisher withdrew: `pubkey|reference` to the newest deletion's time. */\nexport type Withdrawals = ReadonlyMap<string, number>;\n\nconst referenceKey = (pubkey: string, reference: string): string => `${pubkey}|${reference}`;\n\n/**\n * Record what a deletion request withdraws. Only the author's own events and\n * addresses count: a deletion signed by someone else withdraws nothing.\n *\n * @param withdrawals - What was withdrawn so far.\n * @param deletion - A kind 5 event.\n * @returns The withdrawals including this request.\n * @example\n * ```ts\n * let withdrawn: Withdrawals = new Map();\n * withdrawn = withdraw(withdrawn, deletionEvent);\n * ```\n */\nexport function withdraw(withdrawals: Withdrawals, deletion: NostrEvent): Withdrawals {\n const next = new Map(withdrawals);\n for (const [name, value] of deletion.tags) {\n if ((name !== 'e' && name !== 'a') || typeof value !== 'string') continue;\n if (name === 'a' && value.split(':')[1] !== deletion.pubkey) continue;\n const key = referenceKey(deletion.pubkey, value);\n next.set(key, Math.max(next.get(key) ?? 0, deletion.created_at));\n }\n return next;\n}\n\n/**\n * Whether the publisher withdrew this manifest: its id was deleted, or its\n * address was deleted at or after the time it was published.\n *\n * @param event - A manifest event.\n * @param withdrawals - What publishers withdrew.\n * @returns True when the manifest should not be listed.\n * @example\n * ```ts\n * isWithdrawn(manifest, withdraw(new Map(), deletionOfIt)); // true\n * ```\n */\nexport function isWithdrawn(event: NostrEvent, withdrawals: Withdrawals): boolean {\n if (withdrawals.has(referenceKey(event.pubkey, event.id))) return true;\n const identifier = event.tags.find((tag) => tag[0] === 'd')?.[1] ?? '';\n const at = withdrawals.get(referenceKey(event.pubkey, `${event.kind}:${event.pubkey}:${identifier}`));\n return at !== undefined && at >= event.created_at;\n}\n","import type { CatalogEntry } from './entry.js';\n\n/** What the store filters by. Every part is optional; an empty query lists everything. */\nexport interface CatalogQuery {\n /** Free text, matched loosely against title, topics, roles, description and publisher. */\n readonly text?: string;\n /** Topics the entry must carry, all of them. */\n readonly topics?: readonly string[];\n /** When given, entries that require a domain outside this list are left out. */\n readonly available?: readonly string[];\n /** When given, only entries that accept this convention identity, such as `napplet:profile/open`. */\n readonly convention?: string;\n}\n\n/** A topic and how many listed applets carry it. */\nexport interface TopicCount {\n readonly topic: string;\n readonly count: number;\n}\n\nconst FIELD_WEIGHTS = { title: 8, topics: 5, archetypes: 5, description: 2, publisher: 1 } as const;\n\n/**\n * How well one search word matches a field: a whole-word hit beats a prefix,\n * a prefix beats a substring, and a substring beats the word's letters\n * appearing in order within one word of the field, which forgives a typo\n * without letting a long description match anything. Zero when none hold.\n *\n * @param word - One lower-case search word.\n * @param field - Lower-case field text.\n * @returns A score from 0 to 4.\n * @example\n * ```ts\n * fuzzyScore('chess', 'chess club'); // 4\n * fuzzyScore('chss', 'chess club'); // 1\n * ```\n */\nexport function fuzzyScore(word: string, field: string): number {\n if (word === '' || field === '') return 0;\n const words = field.split(/[^\\p{L}\\p{N}]+/u);\n if (words.includes(word)) return 4;\n if (words.some((part) => part.startsWith(word))) return 3;\n if (field.includes(word)) return 2;\n return word.length > 2 && words.some((part) => inOrder(word, part)) ? 1 : 0;\n}\n\n/** Whether every letter of `word` appears in `part`, in order: \"mnswpr\" in \"minesweeper\". */\nfunction inOrder(word: string, part: string): boolean {\n let at = 0;\n for (const char of part) if (char === word[at]) at += 1;\n return at === word.length;\n}\n\nfunction wordScore(word: string, entry: CatalogEntry): number {\n const fields: Record<keyof typeof FIELD_WEIGHTS, string> = {\n title: entry.title.toLowerCase(),\n topics: entry.topics.join(' '),\n archetypes: entry.archetypes.join(' '),\n description: entry.description.toLowerCase(),\n publisher: entry.publisher,\n };\n let best = 0;\n for (const [field, weight] of Object.entries(FIELD_WEIGHTS)) {\n best = Math.max(best, fuzzyScore(word, fields[field as keyof typeof FIELD_WEIGHTS]) * weight);\n }\n return best;\n}\n\nfunction textScore(text: string, entry: CatalogEntry): number {\n const words = text.toLowerCase().split(/\\s+/).filter(Boolean);\n let total = 0;\n for (const word of words) {\n const score = wordScore(word, entry);\n if (score === 0) return 0;\n total += score;\n }\n return words.length === 0 ? 1 : total;\n}\n\nfunction passesFilters(entry: CatalogEntry, query: CatalogQuery): boolean {\n if (query.topics?.some((topic) => !entry.topics.includes(topic))) return false;\n if (query.available && entry.requires.some((domain) => !query.available?.includes(domain))) return false;\n return query.convention === undefined || entry.conventions.includes(query.convention);\n}\n\n/**\n * Filter and rank store entries.\n *\n * Every search word has to match some field; entries are ordered by score,\n * then by how recently they were published.\n *\n * @param entries - The listed applets.\n * @param query - Text, topics, the domains the shell offers and an optional convention.\n * @returns Matching entries, best first.\n * @example\n * ```ts\n * searchCatalog(entries, { text: 'mine swep', topics: ['game'], available: kernl.grants.availableDomains() });\n * ```\n */\nexport function searchCatalog(entries: readonly CatalogEntry[], query: CatalogQuery = {}): readonly CatalogEntry[] {\n const scored: Array<{ entry: CatalogEntry; score: number }> = [];\n for (const entry of entries) {\n if (!passesFilters(entry, query)) continue;\n const score = textScore(query.text ?? '', entry);\n if (score > 0) scored.push({ entry, score });\n }\n scored.sort((a, b) => b.score - a.score || b.entry.publishedAt - a.entry.publishedAt);\n return Object.freeze(scored.map(({ entry }) => entry));\n}\n\n/**\n * The topics most listed applets carry, for the store's filter bubbles.\n *\n * @param entries - The listed applets.\n * @param limit - How many topics to return.\n * @returns Topics by count, then alphabetically.\n * @example\n * ```ts\n * popularTopics(entries, 3); // [{ topic: 'game', count: 14 }, { topic: '3d', count: 5 }, …]\n * ```\n */\nexport function popularTopics(entries: readonly CatalogEntry[], limit = 12): readonly TopicCount[] {\n const counts = new Map<string, number>();\n for (const entry of entries) for (const topic of entry.topics) counts.set(topic, (counts.get(topic) ?? 0) + 1);\n return Object.freeze(\n [...counts]\n .map(([topic, count]) => ({ topic, count }))\n .sort((a, b) => b.count - a.count || a.topic.localeCompare(b.topic))\n .slice(0, limit),\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA,SAAS,oCAAoC;;;ACO7C,SAAS,UAAU,KAAyB;AAC1C,MAAI;AACF,WAAO,EAAE,IAAI,MAAM,OAAO,KAAK,MAAM,GAAG,EAAE;AAAA,EAC5C,QAAQ;AACN,WAAO,EAAE,IAAI,MAAM;AAAA,EACrB;AACF;AAmBO,SAAS,sBAAsB,SAAsB,QAAiC;AAC3F,QAAM,SAAS,CAAC,QAAwB,GAAG,MAAM,IAAI,GAAG;AACxD,SAAO;AAAA,IACL,QAAW,KAAa,UAAgB;AACtC,YAAM,MAAM,QAAQ,QAAQ,OAAO,GAAG,CAAC;AACvC,UAAI,QAAQ,KAAM,QAAO;AACzB,YAAM,SAAS,UAAU,GAAG;AAC5B,aAAO,OAAO,KAAM,OAAO,QAAc;AAAA,IAC3C;AAAA,IACA,QAAQ,KAAK,OAAO;AAClB,cAAQ,QAAQ,OAAO,GAAG,GAAG,KAAK,UAAU,KAAK,CAAC;AAAA,IACpD;AAAA,IACA,OAAO,KAAK;AACV,cAAQ,WAAW,OAAO,GAAG,CAAC;AAAA,IAChC;AAAA,EACF;AACF;;;ACtDA,SAAS,uBAAuB;AAgBzB,IAAM,sBAA+B,OAAO,OAAO;AAAA,EACxD,WAAW,CAAC,sBAAsB,wBAAwB;AAAA;AAAA,E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;AAAA,EAC7C;AACA,SAAO,KAAK,CAAC,GAAG,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,cAAc,EAAE,MAAM,WAAW;AACpF,SAAO,OAAO,OAAO,OAAO,IAAI,CAAC,EAAE,MAAM,MAAM,KAAK,CAAC;AACvD;AAaO,SAAS,cAAc,SAAkC,QAAQ,IAA2B;AACjG,QAAM,SAAS,oBAAI,IAAoB;AACvC,aAAW,SAAS,QAAS,YAAW,SAAS,MAAM,OAAQ,QAAO,IAAI,QAAQ,OAAO,IAAI,KAAK,KAAK,KAAK,CAAC;AAC7G,SAAO,OAAO;AAAA,IACZ,CAAC,GAAG,MAAM,EACP,IAAI,CAAC,CAAC,OAAO,KAAK,OAAO,EAAE,OAAO,MAAM,EAAE,EAC1C,KAAK,CAAC,GAAG,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,cAAc,EAAE,KAAK,CAAC,EAClE,MAAM,GAAG,KAAK;AAAA,EACnB;AACF;;;A9DlHO,IAAM,eAAe;AAWrB,IAAM,0BAAkC,6BAA6B;","names":["BehaviorSubject","newest","text","query","BehaviorSubject","relays","filter","BehaviorSubject","map","normalizeRelayUrl","relays","from","relayUrls","kinds","filter","map","relays","from","BehaviorSubject","relays","relayUrls","lastValueFrom","map","relays","text","text","coordinate","lastValueFrom","map","merge","switchMap","timer","toArray","unique","relays","newest","filter","switchMap","timer","merge","map","relays","lastValueFrom","toArray","newest","text","BehaviorSubject","BehaviorSubject","record","take","resolveWindow","Subject","STORAGE_KEY","Subject","record","getInboxes","getOutboxes","kinds","lastValueFrom","timer","toArray","isReplaceable","lastValueFrom","timer","toArray","isReplaceable","resolveApplet","STORAGE_KEY","kinds","getConversationParticipants","unixNow","summarize","query","lastValueFrom","relays","relays","unixNow","signerOf","query","kinds","getConversationParticipants","relays","kinds","mergeRelaySets","verifyEvent","getConversationParticipants","verifyEvent","getConversationParticipants","kinds","mergeRelaySets","verifyEvent","text","CAPABILITIES","relays","filter","verifyEvent","signed","signerOf","from","query","unixNow","lastValueFrom","toArray","relays","lastValueFrom","toArray","bytesToHex","kinds","mergeRelaySets","text","bytesToHex","mergeRelaySets","filter","relays","kinds","latest","group","CAPABILITIES","unixNow","signerOf","query","query","page","BehaviorSubject","catchError","EMPTY","map","of","switchMap","unixNow","stateFor","of","catchError","EMPTY","switchMap","map","BehaviorSubject","unixNow","relays","from","STORAGE_KEY","read","getProfileContent","unixNow","FOLLOWS","text","lastValueFrom","map","takeUntil","catchError","distinctUntilChanged","EMPTY","endWith","filter","firstValueFrom","ignoreElements","map","merge","Observable","switchMap","take","timer","getOutboxes","getProfileContent","HEX_KEY","getProfileContent","relays","map","getOutboxes","filter","take","switchMap","Observable","distinctUntilChanged","timer","card","catchError","EMPTY","ignoreElements","endWith","firstValueFrom","merge","map","takeUntil","lastValueFrom","relays","filter","PrivateKeySigner","BehaviorSubject","STORAGE_KEY","HEX_KEY","text","BehaviorSubject","lastValueFrom","takeUntil","timer","toArray","decodeEventPointer","verifyEvent","parseJson","text","decodeEventPointer","relays","filter","lastValueFrom","takeUntil","timer","toArray","verifyEvent","newest","verifyEvent","HEX_KEY","invalid","timer","session","filter","relays","verifyEvent","text","relays","verifyEvent","verifyEvent","TIERS","verifyEvent","record","keyOf","relays","BehaviorSubject","map","of","Subject","Subscription","switchMap","createGuardConfig","lastValueFrom","Subject","takeUntil","timer","toArray","verifyEvent","HEX_64","tag","newest","verifyEvent","Subject","lastValueFrom","takeUntil","timer","toArray","BehaviorSubject","STORAGE_KEY","toCatalogEntry","BehaviorSubject","applet","rank","auditTime","catchError","EMPTY","lastValueFrom","map","merge","share","takeUntil","timer","deletion","relays","EMPTY","takeUntil","timer","catchError","merge","auditTime","map","share","lastValueFrom","Subscription","switchMap","map","of","relays","appletOf","record","Subject","BehaviorSubject","createGuardConfig","text","query"]}
|