@kernlize/core 0.12.0 → 0.14.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/README.md +1 -1
- package/dist/{chunk-E7SNLTN2.js → chunk-ALAK4MW6.js} +8 -1
- package/dist/chunk-ALAK4MW6.js.map +1 -0
- package/dist/index.d.ts +1368 -133
- package/dist/index.js +3563 -487
- package/dist/index.js.map +1 -1
- package/dist/wm/index.d.ts +7 -0
- package/dist/wm/index.js +1 -1
- package/package.json +4 -3
- package/dist/chunk-E7SNLTN2.js.map +0 -1
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/grants/domain-capabilities.ts","../src/grants/message-isolation.ts","../src/applesauce/accounts.ts","../src/applesauce/throwaway.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/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/people/person.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/people/locate-recipients.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 { MESSAGES_DOMAIN, MESSAGE_COMPANION_DOMAINS, capabilitiesInForce, domainsInForce, sealsApplet, withheldDomains } from './grants/message-isolation.js';\nexport { KernlAccountManager, PLAINTEXT_KEY_ACCOUNT_TYPES, createKernlAccounts } from './applesauce/accounts.js';\nexport { THROWAWAY_IDENTITY_TYPE, ThrowawayIdentity, createThrowawayIdentity } from './applesauce/throwaway.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 { PERSON_HINT_TIMEOUT_MS, createPeople, parsePerson, type People, type PeopleOptions, type PersonPointer } from './people/person.js';\nexport { locateRecipients } from './people/locate-recipients.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 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 type { Capability } from '@kehto/runtime';\nimport { BASELINE_DOMAINS, capabilitiesForDomains } from './domain-capabilities.js';\n\n/**\n * The domain that lets an applet read and write the person's private messages.\n *\n * @example\n * ```ts\n * grants.get(identity)?.domains.includes(MESSAGES_DOMAIN); // the applet is sealed\n * ```\n */\nexport const MESSAGES_DOMAIN = 'dm';\n\n/**\n * Every domain an applet may hold together with messages. None of them can\n * carry what the applet read to anywhere but the person's own screen and\n * this device: the handshake, messages themselves, which identity is signed\n * in, the theme, the applet's own storage and settings, notifications,\n * keyboard shortcuts, and being handed a request by another applet.\n *\n * It is an allowlist, so a domain kehto adds later is withheld until it is\n * put here on purpose (D-046).\n *\n * @example\n * ```ts\n * MESSAGE_COMPANION_DOMAINS.includes('upload'); // false\n * ```\n */\nexport const MESSAGE_COMPANION_DOMAINS: readonly string[] = Object.freeze(['shell', MESSAGES_DOMAIN, 'identity', 'theme', 'storage', 'config', 'notify', 'keys', 'intent']);\n\n/**\n * Capabilities withheld even inside a companion domain: an applet that reads\n * messages may be handed a request by another applet, never hand one on.\n */\nconst WITHHELD_CAPABILITIES: readonly Capability[] = Object.freeze(['intent:write']);\n\n/**\n * Whether an applet's grants seal it: it holds messages, so it holds nothing\n * that could send them on.\n *\n * @param granted - The domains the person allowed.\n * @returns True when messages are among them.\n * @example\n * ```ts\n * sealsApplet(['dm', 'relay']); // true\n * ```\n */\nexport function sealsApplet(granted: readonly string[]): boolean {\n return granted.includes(MESSAGES_DOMAIN);\n}\n\n/**\n * The domains actually in force for an applet: the baseline plus what the\n * person allowed, cut down to {@link MESSAGE_COMPANION_DOMAINS} when the\n * applet holds messages.\n *\n * @param granted - The domains the person allowed.\n * @param baseline - Domains every applet holds; {@link BASELINE_DOMAINS} by default.\n * @returns The domains in force, baseline first.\n * @example\n * ```ts\n * domainsInForce(['relay']); // ['shell', 'inc', 'theme', 'storage', 'relay']\n * domainsInForce(['dm', 'relay', 'upload']); // ['shell', 'theme', 'storage', 'dm']\n * ```\n */\nexport function domainsInForce(granted: readonly string[], baseline: readonly string[] = BASELINE_DOMAINS): readonly string[] {\n const held = [...new Set([...baseline, ...granted])];\n return Object.freeze(sealsApplet(granted) ? held.filter((domain) => MESSAGE_COMPANION_DOMAINS.includes(domain)) : held);\n}\n\n/**\n * The domains an applet would hold but for messages: allowed by the person\n * or part of the baseline, and not in force while it can read messages.\n *\n * @param granted - The domains the person allowed.\n * @param baseline - Domains every applet holds; {@link BASELINE_DOMAINS} by default.\n * @returns The withheld domains; empty for an applet without messages.\n * @example\n * ```ts\n * withheldDomains(['dm', 'relay']); // ['inc', 'relay']\n * ```\n */\nexport function withheldDomains(granted: readonly string[], baseline: readonly string[] = BASELINE_DOMAINS): readonly string[] {\n const inForce = domainsInForce(granted, baseline);\n return Object.freeze([...new Set([...baseline, ...granted])].filter((domain) => !inForce.includes(domain)));\n}\n\n/**\n * The kehto capabilities an applet's grants come to, after the seal.\n *\n * @param granted - The domains the person allowed.\n * @returns The capabilities to write into the runtime ACL.\n * @example\n * ```ts\n * capabilitiesInForce(['dm', 'intent', 'relay']); // dm, baseline and 'intent:read'; no relay, no 'intent:write'\n * ```\n */\nexport function capabilitiesInForce(granted: readonly string[]): readonly Capability[] {\n const capabilities = capabilitiesForDomains(domainsInForce(granted));\n return sealsApplet(granted) ? capabilities.filter((capability) => !WITHHELD_CAPABILITIES.includes(capability)) : capabilities;\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 { BaseAccount } from 'applesauce-accounts';\nimport type { SerializedAccount } from 'applesauce-accounts';\nimport { getPublicKey } from 'applesauce-core/helpers/keys';\nimport { PrivateKeySigner } from 'applesauce-signers';\n\n/**\n * The type of an identity that is never written down.\n *\n * @example\n * ```ts\n * account.type === THROWAWAY_IDENTITY_TYPE; // true for createThrowawayIdentity()\n * ```\n */\nexport const THROWAWAY_IDENTITY_TYPE = 'throwaway';\n\n/**\n * An identity for trying the shell: a fresh key held by its signer in memory\n * and nowhere else. It signs like any other, so the live store, applets and\n * consent all behave as they will for a kept identity. It refuses to be\n * serialised, so the account manager's persistence skips it and a reload\n * starts without it (D-044).\n *\n * @example\n * ```ts\n * const identity = createThrowawayIdentity();\n * await kernl.login(identity);\n * ```\n */\nexport class ThrowawayIdentity extends BaseAccount<PrivateKeySigner, never, { name: string }> {\n static readonly type = THROWAWAY_IDENTITY_TYPE;\n\n /**\n * Refuse to be written down.\n *\n * @throws `denied:plaintext-key-persistence`, always.\n */\n override toJSON(): SerializedAccount<never, { name: string }> {\n throw new Error('denied:plaintext-key-persistence');\n }\n}\n\n/**\n * Make an identity that lasts until the page goes away.\n *\n * @param name - What the shell calls it until a profile says otherwise.\n * @returns The identity, ready for `kernl.login`.\n * @example\n * ```ts\n * await kernl.login(createThrowawayIdentity('Just looking'));\n * ```\n */\nexport function createThrowawayIdentity(name = 'Just looking'): ThrowawayIdentity {\n const signer = new PrivateKeySigner();\n const identity = new ThrowawayIdentity(getPublicKey(signer.key), signer);\n identity.metadata = { name };\n return identity;\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 { 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 } from './domain-capabilities.js';\nimport { capabilitiesInForce, domainsInForce, withheldDomains } from './message-isolation.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. An applet that holds messages is sealed: only the domains that\n * cannot send what it read anywhere stay in force, and the rest are reported\n * as `withheld` (D-046). 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: capabilitiesInForce(entry.domains),\n withheld: withheldDomains(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>(capabilitiesInForce(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. An\n * applet that holds messages sees only the domains that may go with them.\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'] : domainsInForce(record?.domains ?? [], grants.baselineDomains()));\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 identity 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 identity', 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, 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 /** Reads a person from any form of their identity, asking the servers it names first; `invalid:person` otherwise. */\n readonly locate: (input: string) => Promise<string>;\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\nconst located = (options: CommonActionsOptions, value: string): Promise<string | undefined> => options.locate(value).catch(() => undefined);\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 = await Promise.all(pubkeys.map((key) => located(options, key)));\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 = await located(options, 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 { createPeople, type People } from './people/person.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 people: People;\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 people = createPeople({ store: eventStore, pool });\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, people, 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' | 'people' | 'replaceableLoader' | 'signer'>, consent: SigningConsent): CommonServiceOptions {\n const { eventStore, pool, tiers, accounts } = parts;\n return createCommonActions({\n store: eventStore,\n profiles: network.profiles,\n locate: network.people.locate,\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, EMPTY, lastValueFrom, takeUntil, tap, timer } from 'rxjs';\nimport type { EventStore } from 'applesauce-core';\nimport { decodePointer } from 'applesauce-core/helpers';\nimport type { NostrEvent } from '@napplet/core';\nimport { asFilters, type ApplesaucePool } from '../applesauce/relay-hooks.js';\n\n/** A person, and where whoever shared them said their data is kept. */\nexport interface PersonPointer {\n /** The identity, as 64 lowercase hex characters. */\n readonly pubkey: string;\n /** Servers named alongside the identity; empty when none were. */\n readonly relays: readonly string[];\n}\n\nconst URI_SCHEME = /^nostr:/i;\nconst SOCKET_URL = /^wss?:\\/\\//i;\nconst HEX_KEY = /^[0-9a-f]{64}$/;\nconst NO_RELAYS: readonly string[] = Object.freeze([]);\n\nfunction decodeOrNothing(text: string): ReturnType<typeof decodePointer> | undefined {\n try {\n return decodePointer(text);\n } catch {\n return undefined;\n }\n}\n\n/**\n * The longest the hinted servers are waited for before a lookup goes on\n * without them. An outer bound only: it ends as soon as they have all answered.\n *\n * @example\n * ```ts\n * createPeople({ store, pool, timeoutMs: PERSON_HINT_TIMEOUT_MS });\n * ```\n */\nexport const PERSON_HINT_TIMEOUT_MS = 8_000;\n\n/** What says who a person is and where they read and are written to: profile, server list, message inboxes. */\nconst PERSON_KINDS = [0, 10002, 10050];\n\n/**\n * Read an identity out of what someone typed, pasted or was sent.\n *\n * Every NIP-19 form of a person is one: 64 hex characters, an `npub`, or an\n * `nprofile`, with or without a `nostr:` prefix and in any case. An\n * `nprofile` carries the servers its data is on, which come back as `relays`.\n *\n * @param input - The text.\n * @returns The person, or `undefined` when the text is none of those.\n * @example\n * ```ts\n * parsePerson('npub1…'); // { pubkey: '3bf0…', relays: [] }\n * parsePerson('nostr:nprofile1…'); // { pubkey: '3bf0…', relays: ['wss://relay.example'] }\n * parsePerson('hello'); // undefined\n * ```\n */\nexport function parsePerson(input: string): PersonPointer | undefined {\n const text = input.trim().replace(URI_SCHEME, '').toLowerCase();\n if (HEX_KEY.test(text)) return Object.freeze({ pubkey: text, relays: NO_RELAYS });\n const decoded = decodeOrNothing(text);\n if (decoded?.type === 'npub') return Object.freeze({ pubkey: decoded.data, relays: NO_RELAYS });\n // An address of anything else, or a secret key, is not a person, whatever key it happens to hold.\n if (decoded?.type !== 'nprofile') return undefined;\n // The decoder always gives an nprofile its list of servers, empty when it names none; only the type says otherwise.\n const named = decoded.data.relays as readonly string[];\n return Object.freeze({ pubkey: decoded.data.pubkey, relays: Object.freeze(named.filter((url) => SOCKET_URL.test(url))) });\n}\n\n/** Options for {@link createPeople}. */\nexport interface PeopleOptions {\n /** The shell's event store; what the hinted servers hold is put here, where every lookup reads first. */\n readonly store: EventStore;\n readonly pool: ApplesaucePool;\n /** Outer bound on waiting for the hinted servers; {@link PERSON_HINT_TIMEOUT_MS} by default. */\n readonly timeoutMs?: number;\n}\n\n/** Finds people from any form of their identity. */\nexport interface People {\n /** Read an identity; `undefined` when the text is not one. Asks nobody. */\n parse(input: string): PersonPointer | undefined;\n /**\n * Read an identity and, when it names servers, fetch the person's profile,\n * server list and message inboxes from them first, so whatever looks the\n * person up next finds them.\n *\n * @throws `invalid:person` when the text is not an identity.\n */\n locate(input: string): Promise<string>;\n}\n\n/**\n * Create the shell's way of finding a person from what was typed or sent.\n *\n * The servers an `nprofile` names are asked once per person and set of\n * servers, and what they hold is added to the shell's event store. A server\n * that fails or says nothing costs nothing: the lookup goes on with the\n * shell's own servers, as it would have without the hint.\n *\n * @param options - The event store, the pool and the outer bound.\n * @returns The finder.\n * @example\n * ```ts\n * const people = createPeople({ store: eventStore, pool });\n * const pubkey = await people.locate('nprofile1…');\n * ```\n */\nexport function createPeople(options: PeopleOptions): People {\n const asked = new Map<string, Promise<void>>();\n\n const ask = (person: PersonPointer): Promise<void> => {\n const key = `${person.pubkey}:${[...person.relays].sort().join(',')}`;\n const known = asked.get(key);\n if (known) return known;\n const done = lastValueFrom(\n options.pool.request([...person.relays], asFilters([{ kinds: PERSON_KINDS, authors: [person.pubkey] }])).pipe(\n takeUntil(timer(options.timeoutMs ?? PERSON_HINT_TIMEOUT_MS)),\n tap((event: NostrEvent) => options.store.add(event)),\n catchError(() => EMPTY),\n ),\n { defaultValue: undefined },\n ).then(() => undefined);\n asked.set(key, done);\n return done;\n };\n\n return {\n parse: parsePerson,\n async locate(input) {\n const person = parsePerson(input);\n if (!person) throw new Error('invalid:person');\n if (person.relays.length > 0) await ask(person);\n return person.pubkey;\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 identity' },\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 { locateRecipients } from './people/locate-recipients.js';\nimport type { People } from './people/person.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 /** Reads the people an applet names in any form of their identity; without it only hex is taken. */\n readonly people?: Pick<People, 'locate'>;\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 located = deps.people ? locateRecipients(deps.messaging.composite(), deps.people) : deps.messaging.composite();\n const dm = createDmService({ adapter: deps.profiles ? labelConversations(located, deps.profiles) : located });\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 { DmAdapter } from '@kehto/services';\nimport type { People } from './person.js';\n\n/**\n * Let an applet name the people it writes to in any form of their identity.\n *\n * Every recipient of a send is read with `people.locate`, so hex, `npub` and\n * `nprofile` all work and the servers an `nprofile` names are asked for the\n * person's inboxes before the message is sealed. The backends still see hex.\n *\n * @param adapter - The messaging adapter to wrap.\n * @param people - The shell's finder.\n * @returns The adapter, with recipients read on the way in.\n * @throws `invalid:recipient` from `send` when a recipient is not an identity.\n * @example\n * ```ts\n * createDmService({ adapter: locateRecipients(messaging.composite(), kernl.people) });\n * ```\n */\nexport function locateRecipients(adapter: DmAdapter, people: Pick<People, 'locate'>): DmAdapter {\n return {\n ...adapter,\n async send(request) {\n const recipients = await Promise.all(request.recipients.map((recipient) => people.locate(recipient))).catch(() => {\n throw new Error('invalid:recipient');\n });\n return adapter.send({ ...request, recipients });\n },\n };\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. The one grant that\n * narrows is messages: it withholds every domain that could send them on, so\n * a window started with one of those stops (D-046).\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].filter((domain) => !record.withheld.includes(domain)));\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, people, directory, mailboxes, files, signer } = createKernlNetwork(options, { eventStore, pool, tiers, accounts, destroyed$ });\n const lookupBefore = lookupReplaceable(eventStore, { loader: replaceableLoader, relays: () => [...tiers.get().outbox, ...tiers.get().discovery] });\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 people,\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, people, 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 people,\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,MAA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AAO;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;;;AlElHO,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","PrivateKeySigner","unixNow","summarize","query","lastValueFrom","relays","relays","unixNow","signerOf","query","PrivateKeySigner","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","EMPTY","lastValueFrom","takeUntil","timer","decodePointer","HEX_KEY","text","decodePointer","lastValueFrom","takeUntil","timer","catchError","EMPTY","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","located","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","tap","timer","deletion","relays","EMPTY","takeUntil","timer","catchError","tap","merge","auditTime","map","share","lastValueFrom","Subscription","switchMap","map","of","relays","appletOf","record","Subject","BehaviorSubject","createGuardConfig","text","query"]}
|
|
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/grants/domain-capabilities.ts","../src/grants/message-isolation.ts","../src/applesauce/accounts.ts","../src/applesauce/throwaway.ts","../src/applets/pointer.ts","../src/applets/builtin.ts","../src/applets/resolve.ts","../src/catalog/entry.ts","../src/applets/plan.ts","../src/applets/traffic.ts","../src/applets/mount.ts","../src/firewall/permissions.ts","../src/firewall/describe.ts","../src/guard/pipeline.ts","../src/keys/forwarded-keys.ts","../src/keys/keymap-hold.ts","../src/guard/runtime-rate-limit.ts","../src/firewall/rules.ts","../src/firewall/admission.ts","../src/firewall/firewall.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/people/person.ts","../src/profiles/profiles.ts","../src/multiplayer/remote-tools.ts","../src/multiplayer/window-identities.ts","../src/keys/shortcuts.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/people/locate-recipients.ts","../src/kernl-adapter.ts","../src/kernl-lifecycle.ts","../src/kernl.ts","../src/downloads/bindings.ts","../src/downloads/download-clients.ts","../src/secrets/secrets.ts","../src/downloads/download-records.ts","../src/downloads/nzb-handles.ts","../src/downloads/nzb-wire.ts","../src/downloads/nzb-document.ts","../src/downloads/nzb-replay.ts","../src/downloads/nzb-requests.ts","../src/downloads/nzb-session.ts","../src/downloads/nzb-mutations.ts","../src/downloads/nzb-queries.ts","../src/downloads/nzb-service.ts","../src/downloads/soulseek-queries.ts","../src/downloads/soulseek-transfers.ts","../src/downloads/soulseek-service.ts","../src/downloads/torrent-wire.ts","../src/downloads/torrent-jobs.ts","../src/downloads/torrent-service.ts","../src/kernl-downloads.ts","../src/kernl-firewall.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 { MESSAGES_DOMAIN, MESSAGE_COMPANION_DOMAINS, capabilitiesInForce, domainsInForce, sealsApplet, withheldDomains } from './grants/message-isolation.js';\nexport { KernlAccountManager, PLAINTEXT_KEY_ACCOUNT_TYPES, createKernlAccounts } from './applesauce/accounts.js';\nexport { THROWAWAY_IDENTITY_TYPE, ThrowawayIdentity, createThrowawayIdentity } from './applesauce/throwaway.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, resolveAppletEnvironment, type PlanMountOptions } from './applets/plan.js';\nexport { appletMessageFailure, createAppletTraffic, describeAppletMessage, type AppletMessage, type AppletMessageDirection, type AppletTraffic } from './applets/traffic.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 { createRuntimeRateLimiter, runtimeOpClass, toGuardEvent } from './guard/runtime-rate-limit.js';\nexport { FIREWALL_RULES_STORAGE_KEY, createFirewallRules, defaultFirewallRules, type FirewallRules } from './firewall/rules.js';\nexport { answerFor, describeApproval } from './firewall/describe.js';\nexport {\n FIREWALL_DECISIONS_STORAGE_KEY,\n FIREWALL_PROMPT_TIMEOUT_MS,\n createFirewallPermissions,\n permissionPrincipalFor,\n type FirewallPermissionsOptions,\n} from './firewall/permissions.js';\nexport { MAX_UNMOUNTED_PLANS, createAppletAdmissions, type AdmissionRuntime, type AppletAdmissions } from './firewall/admission.js';\nexport { createFirewall, type FirewallOptions, type KernlFirewall } from './firewall/firewall.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 { KEY_REPEAT_WINDOW_MS, createForwardedKeys, type ForwardedKeys } from './keys/forwarded-keys.js';\nexport { createKeymapHold, type KeymapHold, type KeymapHoldOptions } from './keys/keymap-hold.js';\nexport { createShortcutsService, type ShortcutKey, type ShortcutSettings, type ShortcutsOptions, type ShortcutsService } from './keys/shortcuts.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, acceptAnyRelay, createKernlServices, fetchThroughFirewall, isTheme, resourceErrorFor, resourceInitFor, shellRelayOrigins, 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 { PERSON_HINT_TIMEOUT_MS, createPeople, parsePerson, type People, type PeopleOptions, type PersonPointer } from './people/person.js';\nexport { locateRecipients, locateSendRecipients } from './people/locate-recipients.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';\nexport type { DownloadQuestion, DownloadQuestionLine, DownloadService, DownloadServiceDeps } from './downloads/types.js';\nexport { createDownloadClients, currentPageScheme, DOWNLOAD_PROGRAMS, type CheckedConnection, type ClientFor, type ConnectionChange, type ConnectionRouting, type DownloadClients, type DownloadClientsOptions, type DownloadClientsState, type DownloadConnection, type DownloadDomain, type DownloadProgram, type DownloadProgramInfo, type DownloadSignIn, type RoutedClient, type RoutedDomain } from './downloads/download-clients.js';\nexport { DOWNLOAD_BINDINGS, supportsDomainBindings, type BoundPreludeOptions, type DomainBinding, type DomainBindingMethod } from './downloads/bindings.js';\nexport { createTorrentService, type TorrentServiceOptions } from './downloads/torrent-service.js';\nexport { createNzbService, readNzbDocument, type NzbDocument, type NzbDownloader, type NzbServiceOptions } from './downloads/nzb-service.js';\nexport { createSoulseekService, DEFAULT_SOULSEEK_LIMITS, SOULSEEK_SESSION_QUESTION, type SoulseekLimits, type SoulseekServiceOptions } from './downloads/soulseek-service.js';\nexport { createKernlDownloads, describeDownloadQuestion, DOWNLOAD_DOMAINS, type KernlDownloads, type KernlDownloadsDeps } from './kernl-downloads.js';\nexport type { PlannedExtensions } from './applets/plan.js';\nexport { createMemorySecrets, createStorageSecrets, type SecretsDescription, type SecretsProvider } from './secrets/secrets.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 relay'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 relays` or `No relay 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 relays'\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 relay to save it to';\n if (!outcome.ok) return 'No relay accepted it';\n if (outcome.refused.length > 0) return `Saved to ${outcome.accepted.length} of ${total} relays`;\n return total === 1 ? 'Saved to 1 relay' : `Saved to all ${total} relays`;\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 relays'\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 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 // Not kehto domains at all: its runtime admits each by the window's environment and the service's own message list (D-050).\n torrent: [],\n nzb: [],\n soulseek: [],\n});\n\n/**\n * Domains every applet gets without asking: the handshake, in-shell messaging,\n * the theme, scoped storage and keyboard shortcuts, which act only in the\n * applet's own focused window (D-054). 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', 'keys']);\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 type { Capability } from '@kehto/runtime';\nimport { BASELINE_DOMAINS, capabilitiesForDomains } from './domain-capabilities.js';\n\n/**\n * The domain that lets an applet read and write the person's private messages.\n *\n * @example\n * ```ts\n * grants.get(identity)?.domains.includes(MESSAGES_DOMAIN); // the applet is sealed\n * ```\n */\nexport const MESSAGES_DOMAIN = 'dm';\n\n/**\n * Every domain an applet may hold together with messages. None of them can\n * carry what the applet read to anywhere but the person's own screen and\n * this device: the handshake, messages themselves, which identity is signed\n * in, the theme, the applet's own storage and settings, notifications,\n * keyboard shortcuts, and being handed a request by another applet.\n *\n * It is an allowlist, so a domain kehto adds later is withheld until it is\n * put here on purpose (D-046).\n *\n * @example\n * ```ts\n * MESSAGE_COMPANION_DOMAINS.includes('upload'); // false\n * ```\n */\nexport const MESSAGE_COMPANION_DOMAINS: readonly string[] = Object.freeze(['shell', MESSAGES_DOMAIN, 'identity', 'theme', 'storage', 'config', 'notify', 'keys', 'intent']);\n\n/**\n * Capabilities withheld even inside a companion domain: an applet that reads\n * messages may be handed a request by another applet, never hand one on.\n */\nconst WITHHELD_CAPABILITIES: readonly Capability[] = Object.freeze(['intent:write']);\n\n/**\n * Whether an applet's grants seal it: it holds messages, so it holds nothing\n * that could send them on.\n *\n * @param granted - The domains the person allowed.\n * @returns True when messages are among them.\n * @example\n * ```ts\n * sealsApplet(['dm', 'relay']); // true\n * ```\n */\nexport function sealsApplet(granted: readonly string[]): boolean {\n return granted.includes(MESSAGES_DOMAIN);\n}\n\n/**\n * The domains actually in force for an applet: the baseline plus what the\n * person allowed, cut down to {@link MESSAGE_COMPANION_DOMAINS} when the\n * applet holds messages.\n *\n * @param granted - The domains the person allowed.\n * @param baseline - Domains every applet holds; {@link BASELINE_DOMAINS} by default.\n * @returns The domains in force, baseline first.\n * @example\n * ```ts\n * domainsInForce(['relay']); // ['shell', 'inc', 'theme', 'storage', 'relay']\n * domainsInForce(['dm', 'relay', 'upload']); // ['shell', 'theme', 'storage', 'dm']\n * ```\n */\nexport function domainsInForce(granted: readonly string[], baseline: readonly string[] = BASELINE_DOMAINS): readonly string[] {\n const held = [...new Set([...baseline, ...granted])];\n return Object.freeze(sealsApplet(granted) ? held.filter((domain) => MESSAGE_COMPANION_DOMAINS.includes(domain)) : held);\n}\n\n/**\n * The domains an applet would hold but for messages: allowed by the person\n * or part of the baseline, and not in force while it can read messages.\n *\n * @param granted - The domains the person allowed.\n * @param baseline - Domains every applet holds; {@link BASELINE_DOMAINS} by default.\n * @returns The withheld domains; empty for an applet without messages.\n * @example\n * ```ts\n * withheldDomains(['dm', 'relay']); // ['inc', 'relay']\n * ```\n */\nexport function withheldDomains(granted: readonly string[], baseline: readonly string[] = BASELINE_DOMAINS): readonly string[] {\n const inForce = domainsInForce(granted, baseline);\n return Object.freeze([...new Set([...baseline, ...granted])].filter((domain) => !inForce.includes(domain)));\n}\n\n/**\n * The kehto capabilities an applet's grants come to, after the seal.\n *\n * @param granted - The domains the person allowed.\n * @returns The capabilities to write into the runtime ACL.\n * @example\n * ```ts\n * capabilitiesInForce(['dm', 'intent', 'relay']); // dm, baseline and 'intent:read'; no relay, no 'intent:write'\n * ```\n */\nexport function capabilitiesInForce(granted: readonly string[]): readonly Capability[] {\n const capabilities = capabilitiesForDomains(domainsInForce(granted));\n return sealsApplet(granted) ? capabilities.filter((capability) => !WITHHELD_CAPABILITIES.includes(capability)) : capabilities;\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 { BaseAccount } from 'applesauce-accounts';\nimport type { SerializedAccount } from 'applesauce-accounts';\nimport { getPublicKey } from 'applesauce-core/helpers/keys';\nimport { PrivateKeySigner } from 'applesauce-signers';\n\n/**\n * The type of an identity that is never written down.\n *\n * @example\n * ```ts\n * account.type === THROWAWAY_IDENTITY_TYPE; // true for createThrowawayIdentity()\n * ```\n */\nexport const THROWAWAY_IDENTITY_TYPE = 'throwaway';\n\n/**\n * An identity for trying the shell: a fresh key held by its signer in memory\n * and nowhere else. It signs like any other, so the live store, applets and\n * consent all behave as they will for a kept identity. It refuses to be\n * serialised, so the account manager's persistence skips it and a reload\n * starts without it (D-044).\n *\n * @example\n * ```ts\n * const identity = createThrowawayIdentity();\n * await kernl.login(identity);\n * ```\n */\nexport class ThrowawayIdentity extends BaseAccount<PrivateKeySigner, never, { name: string }> {\n static readonly type = THROWAWAY_IDENTITY_TYPE;\n\n /**\n * Refuse to be written down.\n *\n * @throws `denied:plaintext-key-persistence`, always.\n */\n override toJSON(): SerializedAccount<never, { name: string }> {\n throw new Error('denied:plaintext-key-persistence');\n }\n}\n\n/**\n * Make an identity that lasts until the page goes away.\n *\n * @param name - What the shell calls it until a profile says otherwise.\n * @returns The identity, ready for `kernl.login`.\n * @example\n * ```ts\n * await kernl.login(createThrowawayIdentity('Just looking'));\n * ```\n */\nexport function createThrowawayIdentity(name = 'Just looking'): ThrowawayIdentity {\n const signer = new PrivateKeySigner();\n const identity = new ThrowawayIdentity(getPublicKey(signer.key), signer);\n identity.metadata = { name };\n return identity;\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 type ShellEnvironment,\n} from '@kehto/shell';\nimport { createAppletCsp, renderInsertionLockScript, type GuardProfile } from '@kernlize/guard';\nimport { renderRandomUuidFallbackScript } from '../crypto/install.js';\nimport type { BoundPreludeOptions, DomainBinding } from '../downloads/bindings.js';\nimport type { AppletSummary, MountPlan } from '../types.js';\n\n/** Domains kernl serves that kehto's shell does not list, as one applet is to see them. */\nexport interface PlannedExtensions {\n /** The extension domains in force for this applet, already narrowed by its grants. */\n readonly domains: readonly string[];\n /** What each one offers inside the applet. */\n readonly bindings: Readonly<Record<string, DomainBinding>>;\n}\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 /** Domains beyond kehto's own to add to the applet's environment and bind in its namespace. */\n readonly extensions?: PlannedExtensions;\n /** The domains the firewall admitted the applet with; the environment is narrowed to them. Everything the grants leave when absent. */\n readonly domains?: readonly 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, prelude: BoundPreludeOptions): string {\n const head = renderNappletCspMeta(csp, true) + renderNappletNamespacePrelude(prelude);\n return spliceOnce(srcdoc, head, head + renderInsertionLockScript() + renderRandomUuidFallbackScript());\n}\n\n/** The bindings for exactly the extension domains this applet holds; none leaves the prelude as kehto renders it alone. */\nfunction bindingsFor(extensions: PlannedExtensions | undefined): Pick<BoundPreludeOptions, 'bindings'> {\n const held = Object.entries(extensions?.bindings ?? {}).filter(([domain]) => extensions?.domains.includes(domain));\n return held.length > 0 ? { bindings: Object.fromEntries(held) } : {};\n}\n\n/**\n * The environment an applet is offered before the firewall admits it: kehto's\n * live domains narrowed by the host's `capabilities.resolveEnvironment`,\n * which in kernl is the grants layer.\n *\n * @param adapter - The shell adapter.\n * @param summary - The verified applet.\n * @returns The environment the grants leave the applet.\n * @example\n * ```ts\n * resolveAppletEnvironment(adapter, summary).capabilities.domains; // ['shell', 'identity', 'theme', …]\n * ```\n */\nexport function resolveAppletEnvironment(adapter: ShellAdapter, summary: Pick<AppletSummary, 'identity'>): ShellEnvironment {\n return resolveShellEnvironment(adapter, { dTag: summary.identity.dTag, aggregateHash: summary.identity.hash });\n}\n\n/** Keep only the domains the firewall admitted; everything when it was not asked. */\nfunction narrowEnvironment(environment: ShellEnvironment, domains: readonly string[] | undefined): ShellEnvironment {\n if (!domains) return environment;\n const kept = environment.capabilities.domains.filter((domain) => domains.includes(domain));\n return { ...environment, capabilities: { ...environment.capabilities, domains: kept } };\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), and then by `domains` when the firewall admitted fewer. 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 * `extensions` adds the domains kernl serves beyond kehto's list, with the\n * bindings kehto's prelude turns into `window.napplet.<domain>` (D-050).\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 // The firewall admitted kehto's domains and the extension domains together; the plan holds only what it admitted (D-056).\n const live = narrowEnvironment(resolveAppletEnvironment(options.adapter, summary), options.domains);\n const domains = Object.freeze([...live.capabilities.domains, ...(options.extensions?.domains ?? [])]);\n // kehto reads a window's domains from the environment the host sets at mount, so an extension domain is admitted by being in it.\n const environment = Object.freeze({ capabilities: Object.freeze({ domains }), services: live.services });\n const prelude: BoundPreludeOptions = { domains, experimental: NESTED_CONTEXT_LOCK, ...bindingsFor(options.extensions) };\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, { ...prelude, csp }), csp, prelude),\n sandbox: 'allow-scripts',\n environment,\n missingRequired: Object.freeze(summary.requires.filter((domain) => !domains.includes(domain))),\n };\n}\n","import { Subject, type Observable } from 'rxjs';\nimport { originRegistry } from '@kehto/shell';\n\n/** Which way a message went, from the applet's side. */\nexport type AppletMessageDirection = 'from-applet' | 'to-applet';\n\n/**\n * One message between an applet and the shell. `via` is the channel: `window` for a window-level\n * message (NIP-5D allows one, `napplet.hello`), `port` for everything on the bound port.\n */\nexport interface AppletMessage {\n readonly windowId: string;\n readonly direction: AppletMessageDirection;\n readonly via: 'window' | 'port';\n /** The envelope's `type`, or `unknown` for anything that is not an envelope. */\n readonly type: string;\n /** What failed, when the envelope reports a failure; see {@link appletMessageFailure}. */\n readonly error?: string;\n /** The message itself. It can hold private messages, signed events and stored values: keep it in memory only. */\n readonly message: unknown;\n readonly at: number;\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value);\nconst text = (value: unknown): string | undefined => (typeof value === 'string' && value.length > 0 ? value : undefined);\n\n/**\n * What an envelope says failed: its `error` string, or for a `*.error` envelope its `message`,\n * its `reason` or its type. kehto's runtime answers a failed request with a `*.result` carrying\n * `error`, so this covers its replies; kehto's own devtools read envelopes the same way.\n *\n * @param message - Any message an applet sent or received.\n * @returns The failure, or `undefined` when the message reports none.\n * @example\n * ```ts\n * appletMessageFailure({ type: 'inc.channel.open.result', id: '1', error: 'target denied' }); // 'target denied'\n * appletMessageFailure({ type: 'storage.get.result', id: '2', value: 'x' }); // undefined\n * ```\n */\nexport function appletMessageFailure(message: unknown): string | undefined {\n if (!isRecord(message)) return undefined;\n const error = text(message.error);\n if (error) return error;\n const type = text(message.type);\n if (!type?.endsWith('.error')) return undefined;\n return text(message.message) ?? text(message.reason) ?? type;\n}\n\n/**\n * Describe one message for {@link AppletMessage} reporting, timestamped now.\n *\n * @param windowId - The applet's window.\n * @param direction - Which way it went.\n * @param via - The channel it went over.\n * @param message - The message itself.\n * @returns The report.\n * @example\n * ```ts\n * describeAppletMessage('applet-1', 'to-applet', 'port', { type: 'shell.init', id: '1' }).type; // 'shell.init'\n * ```\n */\nexport function describeAppletMessage(windowId: string, direction: AppletMessageDirection, via: AppletMessage['via'], message: unknown): AppletMessage {\n const type = isRecord(message) ? text(message.type) : undefined;\n const error = appletMessageFailure(message);\n return { windowId, direction, via, type: clip(type ?? 'unknown', TYPE_LIMIT), message, at: Date.now(), ...(error ? { error: clip(error, ERROR_LIMIT) } : {}) };\n}\n\n// An applet chooses its envelopes' `type` and `error`; neither is let grow without bound.\nconst TYPE_LIMIT = 128;\nconst ERROR_LIMIT = 512;\nconst clip = (value: string, limit: number): string => (value.length > limit ? `${value.slice(0, limit)}…` : value);\n\ntype Outgoing = (windowId: string, message: unknown) => void;\ntype Send = typeof originRegistry.postToNapplet;\n\n/** The wrapper in place now, its listeners, and what it wrapped. */\nlet installed: { readonly wrapper: Send; readonly original: Send; readonly listeners: Set<Outgoing> } | undefined;\n\n/**\n * Hear every message kehto sends to an applet. kehto's shell adapter has an observe-only hook for\n * what arrives on a port (`onNappletMessage`) and none for what it sends, so this wraps\n * `originRegistry.postToNapplet`, the one function every reply goes through, as kehto's own devtools\n * do. The wrapper is shared by every shell on the page and removed when the last one stops listening,\n * unless something wrapped it in turn, which is then left in place with the wrapper gone quiet.\n * Only what kehto delivered is heard.\n */\nfunction hearOutgoing(listener: Outgoing): () => void {\n if (!installed) {\n const original = originRegistry.postToNapplet;\n const listeners = new Set<Outgoing>();\n const wrapper: Send = (windowId, message) => {\n const delivered = original.call(originRegistry, windowId, message);\n if (delivered) for (const each of listeners) each(windowId, message);\n return delivered;\n };\n originRegistry.postToNapplet = wrapper;\n installed = { wrapper, original, listeners };\n }\n const { listeners } = installed;\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n if (listeners.size > 0 || installed?.listeners !== listeners) return;\n if (originRegistry.postToNapplet === installed.wrapper) originRegistry.postToNapplet = installed.original;\n installed = undefined;\n };\n}\n\n/** The shell's side of {@link AppletMessage} reporting. */\nexport interface AppletTraffic {\n readonly traffic$: Observable<AppletMessage>;\n /** Report a message an applet sent. */\n fromApplet(windowId: string, via: AppletMessage['via'], message: unknown): void;\n /** Stop reporting; idempotent. */\n close(): void;\n}\n\n/**\n * Report what this shell's applets send and receive, for the windows `owns` accepts. Window ids\n * are counted per shell, so two shells on one page can both have an `applet-1` and would each hear\n * the other's; a host runs one shell per page.\n *\n * @param owns - Whether a window belongs to this shell.\n * @returns The stream and the hooks that feed it.\n * @example\n * ```ts\n * const traffic = createAppletTraffic((windowId) => handles.has(windowId));\n * traffic.traffic$.subscribe((message) => log.push(message));\n * ```\n */\nexport function createAppletTraffic(owns: (windowId: string) => boolean): AppletTraffic {\n const traffic$ = new Subject<AppletMessage>();\n const stop = hearOutgoing((windowId, message) => {\n if (owns(windowId)) traffic$.next(describeAppletMessage(windowId, 'to-applet', 'port', message));\n });\n return {\n traffic$: traffic$.asObservable(),\n fromApplet: (windowId, via, message) => traffic$.next(describeAppletMessage(windowId, 'from-applet', via, message)),\n close() {\n stop();\n traffic$.complete();\n },\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, AppletStopDetails, FrameLike, MountPlan } from '../types.js';\nimport { permissionPrincipalFor } from '../firewall/permissions.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, details?: AppletStopDetails) => 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, details?: AppletStopDetails): 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 const { identity } = plan.summary;\n // The principal is what kehto's firewall knows the applet by; it comes from the verified manifest (D-056).\n deps.originRegistry.register(win, windowId, { dTag: identity.dTag, aggregateHash: identity.hash, permissionPrincipal: permissionPrincipalFor(plan.summary) });\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 // A closed or stopped applet's guard state is forgotten; a late report must not bring it back.\n setVisibility: (visibility) => {\n if (!finished) deps.guard.setVisibility(windowId, visibility);\n },\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, details) {\n if (finished) return;\n teardown('revoked');\n deps.onRevoked?.(windowId, reason, details);\n },\n };\n}\n","import type { ApprovalAnswer, ApprovalPrompt, PermissionAdapter, PermissionRateEvent, PermissionStorageFailure, TemporalPolicy } from '@kehto/runtime';\nimport type { PermissionPrincipal } from '@kehto/firewall';\nimport { createRateLimiter, defaultPromptRateLimitConfig } from '@kehto/rate-limit';\nimport type { AppletSummary, FirewallApplet, KernlHost } from '../types.js';\nimport { answerFor, describeApproval } from './describe.js';\nimport type { FirewallRules } from './rules.js';\n\n/**\n * Where the answers the person asked the firewall to keep are stored.\n *\n * @example\n * ```ts\n * localStorage.getItem(FIREWALL_DECISIONS_STORAGE_KEY); // kehto's serialised grants; only `allow-always` answers are in it\n * ```\n */\nexport const FIREWALL_DECISIONS_STORAGE_KEY = 'kernl:firewall-decisions:v1';\n\n/**\n * How long a firewall question may wait for the person, queue time included.\n * kehto's own default is a minute, which takes a question away from someone\n * who looked elsewhere; kernl only gives up on one nobody is coming back to.\n *\n * @example\n * ```ts\n * FIREWALL_PROMPT_TIMEOUT_MS; // 600000\n * ```\n */\nexport const FIREWALL_PROMPT_TIMEOUT_MS = 10 * 60_000;\n\n/**\n * The identity kehto's firewall knows an applet by: its catalogue id, which\n * rules follow across versions, and the hash of the exact code, which stored\n * answers are tied to. Both come from the verified manifest, never from\n * anything the applet sent.\n *\n * @param summary - A summary this shell verified.\n * @returns The principal to register with the applet's session.\n * @example\n * ```ts\n * permissionPrincipalFor(summary); // { kind: 'verified', manifestKey: 'nip5d:35129:…:notes', artifactHash: '…' }\n * ```\n */\nexport function permissionPrincipalFor(summary: Pick<AppletSummary, 'identity' | 'manifest'>): PermissionPrincipal {\n return { kind: 'verified', manifestKey: summary.manifest.catalogId, artifactHash: summary.identity.hash };\n}\n\nconst STORAGE_FAILURES: Readonly<Record<PermissionStorageFailure, string>> = Object.freeze({\n 'load-failed': 'They could not be read. Applets are refused until you clear them.',\n 'invalid-state': 'They are damaged. Applets are refused until you clear them.',\n 'unsupported-version': 'A newer shell wrote them. Applets are refused until you clear them.',\n 'save-failed': 'That answer could not be stored, so it was not applied.',\n 'storage-unavailable': 'This browser keeps no stored answers, so \"always\" cannot be given.',\n});\n\n/** Options for {@link createFirewallPermissions}. */\nexport interface FirewallPermissionsOptions {\n readonly host: Pick<KernlHost, 'storage' | 'presentApproval' | 'notify' | 'now'>;\n readonly rules: Pick<FirewallRules, 'decide'>;\n /** The applet a principal belongs to, from what this shell planned; `undefined` for one it does not know. */\n readonly appletOf: (principal: PermissionPrincipal) => FirewallApplet | undefined;\n /** Budgets for what the runtime carries out; see `createRuntimeRateLimiter`. */\n readonly rateLimiter: TemporalPolicy;\n /** Receives every spent budget, the question budget included. */\n readonly onRateLimit: (event: PermissionRateEvent) => void;\n}\n\n/**\n * kehto's approval adapter for kernl: the firewall's host side.\n *\n * A request no stored answer covers goes to the rules first. What they allow\n * goes ahead, what they deny is refused, and what they say to ask about is\n * put to the person through `host.presentApproval`; a host without one has\n * such a request refused, never allowed. A question for an applet this shell\n * did not plan is cancelled. \"Always\" answers are kept under\n * {@link FIREWALL_DECISIONS_STORAGE_KEY}; a failed write is told to the person\n * and grants nothing. An applet that asks too often has its questions dropped\n * by kehto's suggested budget, twelve a minute.\n *\n * @param options - Host, rules, the applet lookup and the runtime's rate limiter.\n * @returns The adapter for `ShellAdapter.permissions`.\n * @example\n * ```ts\n * const permissions = createFirewallPermissions({ host, rules, appletOf, rateLimiter, onRateLimit });\n * const adapter: ShellAdapter = { ...rest, permissions };\n * ```\n */\nexport function createFirewallPermissions(options: FirewallPermissionsOptions): PermissionAdapter {\n const { host } = options;\n const present = host.presentApproval?.bind(host);\n const ask = (present: NonNullable<KernlHost['presentApproval']>) => (prompt: ApprovalPrompt): Promise<ApprovalAnswer> => {\n const applet = options.appletOf(prompt.request.principal);\n if (!applet) return Promise.resolve({ effect: 'cancel' });\n const summary = describeApproval(prompt, applet);\n return new Promise((resolve) => {\n const withdrawn = (): void => resolve({ effect: 'cancel' });\n prompt.signal.addEventListener('abort', withdrawn, { once: true });\n present({\n summary,\n signal: prompt.signal,\n resolve(choice) {\n prompt.signal.removeEventListener('abort', withdrawn);\n resolve(answerFor(summary, choice));\n },\n });\n });\n };\n return {\n now: host.now ? host.now.bind(host) : Date.now,\n createCancellation: () => new AbortController(),\n schedule(callback, delayMs) {\n const timer = setTimeout(callback, delayMs);\n return () => clearTimeout(timer);\n },\n timeoutMs: FIREWALL_PROMPT_TIMEOUT_MS,\n ...(present ? { prompt: ask(present) } : {}),\n defaultDecision: (request, missing) => options.rules.decide(request, missing),\n persistence: {\n load: () => host.storage.getItem(FIREWALL_DECISIONS_STORAGE_KEY),\n persist: (serialized) => host.storage.setItem(FIREWALL_DECISIONS_STORAGE_KEY, serialized),\n },\n onStorageError: (failure) => host.notify({ title: 'Firewall: stored answers', body: STORAGE_FAILURES[failure], tone: 'warning' }),\n rateLimiter: options.rateLimiter,\n promptRateLimiter: createRateLimiter(defaultPromptRateLimitConfig()),\n onRateLimit: options.onRateLimit,\n };\n}\n","import type { ApprovalAnswer, ApprovalPrompt, PermissionRequirement } from '@kehto/runtime';\nimport type { FirewallApplet, FirewallChoice, FirewallRequest, FirewallSummary } from '../types.js';\n\nconst ANSWERS: Readonly<Record<FirewallChoice, ApprovalAnswer>> = Object.freeze({\n 'allow-once': { effect: 'allow', lifetime: 'once' },\n 'allow-session': { effect: 'allow', lifetime: 'session' },\n 'allow-always': { effect: 'allow', lifetime: 'persistent' },\n deny: { effect: 'deny', lifetime: 'once' },\n});\n\nconst ALLOW_CHOICES: readonly (readonly [ApprovalPrompt['allowLifetimes'][number], FirewallChoice])[] = [\n ['once', 'allow-once'],\n ['session', 'allow-session'],\n ['persistent', 'allow-always'],\n];\n\nfunction toRequest(requirement: PermissionRequirement): FirewallRequest {\n const kind = requirement.category === 'interface' ? 'access' : requirement.category === 'network' ? 'network' : 'resource';\n return { kind, domain: requirement.domain, operation: requirement.operation, target: requirement.scope.value };\n}\n\nfunction isLink(requests: readonly FirewallRequest[]): boolean {\n return requests.length > 0 && requests.every((request) => request.operation === 'link.open');\n}\n\n/**\n * Turn kehto's approval prompt into what the host shows: who is asking, what\n * for, and which answers are open.\n *\n * The summary carries no copy. Domains and requests are named by their\n * identifiers and the host words them, as it already words grants. A link is\n * answered for that one opening only, whatever lifetimes kehto offers, because\n * the shell asks about every link (D-056). Anything else offers each lifetime\n * kehto allows: once, while the applet stays open, and always when answers\n * can be stored. An applet starting up is never offered `once`, because kehto\n * admits a start for the whole run.\n *\n * @param prompt - What kehto's approval coordinator asks.\n * @param applet - The applet the request came from, as the shell knows it.\n * @returns The summary for `KernlHost.presentApproval`.\n * @example\n * ```ts\n * const summary = describeApproval(prompt, { title: 'Notes', catalogId, identity });\n * summary.kind; // 'link'\n * summary.choices; // ['allow-once', 'deny']\n * ```\n */\nexport function describeApproval(prompt: Pick<ApprovalPrompt, 'missing' | 'allowLifetimes'>, applet: FirewallApplet): FirewallSummary {\n const requests = prompt.missing.map(toRequest);\n if (isLink(requests)) return { kind: 'link', applet, requests, choices: ['allow-once', 'deny'] };\n const offered = ALLOW_CHOICES.filter(([lifetime]) => prompt.allowLifetimes.includes(lifetime)).map(([, choice]) => choice);\n const kind = requests.every((request) => request.kind === 'access') ? 'access' : 'request';\n return { kind, applet, requests, choices: [...offered, 'deny'] };\n}\n\n/**\n * The answer kehto gets for the choice the person made. Dismissing the prompt,\n * or naming a choice it did not offer, cancels the request without storing\n * anything, so the applet may ask again.\n *\n * @param summary - The summary the host was shown.\n * @param choice - What the person chose, or `undefined` when they dismissed it.\n * @returns kehto's approval answer.\n * @example\n * ```ts\n * answerFor(summary, 'allow-once'); // { effect: 'allow', lifetime: 'once' }\n * answerFor(summary, undefined); // { effect: 'cancel' }\n * ```\n */\nexport function answerFor(summary: Pick<FirewallSummary, 'choices'>, choice: FirewallChoice | undefined): ApprovalAnswer {\n if (choice === undefined || !summary.choices.includes(choice)) return { effect: 'cancel' };\n return ANSWERS[choice];\n}\n","import { BehaviorSubject, type Observable } from 'rxjs';\nimport type { NappletMessageDecision } from '@kehto/shell';\nimport {\n classifyEnvelope,\n createFocusRateLimiter,\n createGuardConfig,\n createIngressGuard,\n createVisibilityGate,\n estimateEnvelopeSize,\n type AdmitOptions,\n type FocusRateLimiter,\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';\nimport { createForwardedKeys } from '../keys/forwarded-keys.js';\nimport { createKeymapHold } from '../keys/keymap-hold.js';\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 /**\n * Called once when a window crosses the quarantine threshold; kernl revokes it here, before the\n * triggering envelope is dispatched. `reason` is the guard's: `flood:quarantine` or `flood:hidden-resource`.\n */\n readonly onQuarantine?: (windowId: string, napplet: string, reason: 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, and a shortcut registration from a\n * window in its first second until that second is over (D-054). `drop` discards an envelope over its\n * size cap, a forwarded key that is a held key's repeat or comes from a\n * window that is not focused (D-054), a burst above the per-second rate, a request over the\n * focus-aware rate limiter'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 rateLimiter: FocusRateLimiter;\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 rate limiter.\n */\nfunction judgePort(port: PortEnvelope, admitted: GuardDisposition, rateLimiter: FocusRateLimiter, 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') rateLimiter.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 rateLimiter.observe(windowId, napplet, envelope, visibility).decision === 'pass' ? 'dispatch' : 'drop';\n}\n\nfunction 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\nfunction 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/**\n * How long a window's keymap waits after the window starts: its first second\n * (D-054). The wait was the legacy rate gate's startup window, which kehto's\n * runtime no longer has under the firewall (D-056); one second is what that\n * window was in every profile, and what the keymap is held for still.\n */\nconst KEYMAP_HOLD_MS = 1000;\n\n/**\n * What the pipeline does with shortcut traffic before the guard counts anything\n * (D-054). A held key is the person's typing, not the applet's traffic, so its\n * repeats are dropped; an applet's keymap arrives as it starts, so it waits out\n * the window's first second.\n */\nfunction createKeyTraffic(startupMs: () => number, release: (windowId: string) => void) {\n const forwarded = createForwardedKeys();\n const keymap = createKeymapHold({ startupMs, release });\n return {\n decide(windowId: string, message: unknown, focused: boolean, at: number): NappletMessageDecision | undefined {\n if (forwarded.drops(windowId, message, focused, at)) return 'drop';\n return keymap.holds(windowId, message, at) ? 'defer' : undefined;\n },\n holding: keymap.holding,\n forget(windowId: string): void {\n forwarded.forget(windowId);\n keymap.forget(windowId);\n },\n };\n}\n\n/**\n * The ingress guard says why it quarantined only in its event, emitted inside `admit`, so the\n * pipeline keeps the last quarantine reason for the callback that follows.\n */\nfunction trackQuarantines(sink: ((event: GuardEvent) => void) | undefined): { readonly onEvent: (event: GuardEvent) => void; reason(): string } {\n let last = '';\n return {\n onEvent(event) {\n if (event.disposition === 'quarantine') last = event.reason;\n sink?.(event);\n },\n reason: () => last,\n };\n}\n\n/**\n * Compose the guard: ingress flood control, then the visibility gate, then the\n * focus-aware rate limiter, 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. kehto's runtime then charges what it\n * carries out against the same budgets (`createRuntimeRateLimiter`), held\n * envelopes included, and puts each request to the firewall.\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 handOn = (windowId: string): void => options.onRelease?.(windowId);\n // A hidden window's envelopes stay held; becoming visible hands them on with the keymap.\n const keys = createKeyTraffic(() => KEYMAP_HOLD_MS, (windowId) => visibilityOf(windowId).visible && handOn(windowId));\n const quarantines = trackQuarantines(options.onEvent);\n const layerOptions = () => ({\n config,\n ...(options.now ? { now: options.now } : {}),\n onEvent: quarantines.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 rateLimiter: createFocusRateLimiter(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 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 pastRateLimiter(windowId, pending);\n }\n\n function pastRateLimiter(windowId: string, pending: Pending): GuardDisposition {\n const result = layers.rateLimiter.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, quarantines.reason());\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)) pastRateLimiter(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 visibility = visibilityOf(windowId);\n const shortcut = keys.decide(windowId, message, visibility.focused, clock());\n if (shortcut) return shortcut;\n const envelope = toEnvelope(message);\n const port: PortEnvelope = { windowId, napplet, envelope, visibility };\n return judgePort(port, admit(windowId, napplet, envelope, { hold: false }), layers.rateLimiter, 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 // kehto hands on everything it holds for a window at once, so a held keymap keeps the rest until its wait is over.\n if (!keys.holding(windowId)) handOn(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.rateLimiter.forget(windowId);\n keys.forget(windowId);\n heldByIngress.delete(windowId);\n heldByGate.delete(windowId);\n known.delete(windowId);\n },\n drainAll,\n };\n}\n","/**\n * How long after a forwarded key the same key counts as its repeat. A held key\n * first repeats after the system's delay, at most about half a second, and then\n * many times a second.\n *\n * @example\n * ```ts\n * KEY_REPEAT_WINDOW_MS; // 600\n * ```\n */\nexport const KEY_REPEAT_WINDOW_MS = 600;\n\n/** Decides which `keys.forward` envelopes never reach the guard or the runtime. */\nexport interface ForwardedKeys {\n /**\n * Whether an envelope is a forwarded key to discard: one from a window that\n * is not the focused one, or the repeat of the key that window forwarded last.\n */\n drops(windowId: string, message: unknown, focused: boolean, at: number): boolean;\n /** Forget a window's last key. */\n forget(windowId: string): void;\n}\n\nfunction chordOf(message: Record<string, unknown>): string {\n return [message.key, message.code, message.ctrl, message.alt, message.shift, message.meta].join('|');\n}\n\n/**\n * The filter in front of the guard for keys an applet forwards (D-054).\n *\n * The frame forwards every key it has no binding for, repeats included, so a\n * held key arrives faster than any budget; counted like other traffic it would\n * use up the applet's allowance and then quarantine it for the person's own\n * typing. A repeat is discarded here, uncounted: the shell's shortcuts act on\n * the press. So is a key from a window that is not focused, which the person\n * cannot have typed there.\n *\n * @returns The filter.\n * @example\n * ```ts\n * const forwarded = createForwardedKeys();\n * forwarded.drops('w1', { type: 'keys.forward', key: 'a', code: 'KeyA' }, true, 0); // false: the press\n * forwarded.drops('w1', { type: 'keys.forward', key: 'a', code: 'KeyA' }, true, 500); // true: its repeat\n * ```\n */\nexport function createForwardedKeys(): ForwardedKeys {\n const last = new Map<string, { readonly chord: string; readonly at: number }>();\n return {\n drops(windowId, message, focused, at) {\n if (typeof message !== 'object' || message === null) return false;\n const envelope = message as Record<string, unknown>;\n if (envelope.type !== 'keys.forward') return false;\n if (!focused) return true;\n const chord = chordOf(envelope);\n const previous = last.get(windowId);\n // A repeat renews the window, so the key stays a repeat for as long as it is held.\n last.set(windowId, { chord, at });\n return previous !== undefined && previous.chord === chord && at - previous.at < KEY_REPEAT_WINDOW_MS;\n },\n forget: (windowId) => void last.delete(windowId),\n };\n}\n","/** Options for {@link createKeymapHold}. */\nexport interface KeymapHoldOptions {\n /** How long the runtime's startup burst guard watches a new window, in milliseconds. */\n readonly startupMs: () => number;\n /** Called once a window's startup window has passed, to hand on what was held for it. */\n readonly release: (windowId: string) => void;\n}\n\n/** Holds an applet's shortcut registrations until the runtime will take them. */\nexport interface KeymapHold {\n /**\n * Note an envelope from a window and say whether to hold it: a shortcut\n * registration from a window whose startup window has not passed.\n */\n holds(windowId: string, message: unknown, at: number): boolean;\n /** Whether registrations are being held for a window right now. */\n holding(windowId: string): boolean;\n /** Forget a window and stop waiting for it. */\n forget(windowId: string): void;\n}\n\ninterface Startup {\n readonly firstSeen: number;\n timer?: ReturnType<typeof setTimeout>;\n passed: boolean;\n}\n\nconst REGISTRATIONS: ReadonlySet<unknown> = new Set(['keys.registerAction', 'keys.unregisterAction']);\n\nfunction isRegistration(message: unknown): boolean {\n return typeof message === 'object' && message !== null && REGISTRATIONS.has((message as { type?: unknown }).type);\n}\n\n/**\n * The wait in front of the runtime for an applet's keymap (D-054).\n *\n * An applet registers its shortcuts as it starts, a dozen or more at once,\n * which is exactly when the runtime's startup burst guard lets fewest\n * envelopes through and answers none of the ones it refuses. Registrations\n * that arrive in a window's startup window are held, in order, and handed on\n * together when it has passed, where they meet the ordinary rates. Everything\n * registered later goes straight through.\n *\n * @param options - The length of the startup window and what to do when it has passed.\n * @returns The hold.\n * @example\n * ```ts\n * const hold = createKeymapHold({ startupMs: () => 1000, release: (windowId) => bridge.releaseDeferred(windowId) });\n * hold.holds('w1', { type: 'keys.registerAction' }, Date.now()); // true: held until the window's first second is over\n * ```\n */\nexport function createKeymapHold(options: KeymapHoldOptions): KeymapHold {\n const windows = new Map<string, Startup>();\n return {\n holds(windowId, message, at) {\n let startup = windows.get(windowId);\n if (!startup) {\n startup = { firstSeen: at, passed: false };\n windows.set(windowId, startup);\n }\n if (startup.passed || !isRegistration(message)) return false;\n // One wait per window: a registration that arrives while others are held joins them, so none overtakes another.\n if (startup.timer !== undefined) return true;\n const remaining = options.startupMs() - (at - startup.firstSeen);\n if (remaining <= 0) {\n startup.passed = true;\n return false;\n }\n const waiting = startup;\n waiting.timer = setTimeout(() => {\n delete waiting.timer;\n waiting.passed = true;\n options.release(windowId);\n }, remaining);\n return true;\n },\n holding: (windowId) => windows.get(windowId)?.timer !== undefined,\n forget(windowId) {\n clearTimeout(windows.get(windowId)?.timer);\n windows.delete(windowId);\n },\n };\n}\n","import type { PermissionRateEvent, TemporalPolicy } from '@kehto/runtime';\nimport { createRateLimitState, evaluateRateLimit, retireRateLimitLifecycle, type RateLimitConfig } from '@kehto/rate-limit';\nimport { classifyEnvelope, type GuardConfig, type GuardEvent, type OpClass } from '@kernlize/guard';\n\n/*\n * kehto's runtime builds no rate limiter of its own: a host that wants one\n * constructs it from `@kehto/rate-limit` and hands it over as\n * `permissions.rateLimiter`. Everything kernl puts there lives in this module.\n */\n\n/**\n * The guard's operation class for a request as kehto's runtime names it.\n *\n * The runtime charges an operation by the name its service gave it, which for\n * the requests an applet sends is the envelope's type (`relay.publish`,\n * `storage.set`), so the guard's own classification applies. It does not say\n * what kind of post a publish carries, so deletions share the `relay:publish`\n * budget here; kernl's own rate limiter, in front, keeps their separate one.\n *\n * @param operation - The operation name from a runtime observation.\n * @returns The class whose budget the operation spends.\n * @example\n * ```ts\n * runtimeOpClass('relay.publish'); // 'relay:publish'\n * runtimeOpClass('resource.network'); // 'resource:bytes'\n * runtimeOpClass('link.open'); // 'generic'\n * ```\n */\nexport function runtimeOpClass(operation: string): OpClass {\n return classifyEnvelope({ type: operation });\n}\n\n/**\n * Operations the runtime names for a second leg of work it already charged.\n * A download is charged as `resource.bytes`; approving the server it contacts\n * is the same download, so it spends nothing more.\n */\nconst SECOND_LEGS: ReadonlySet<string> = new Set(['resource.network']);\n\nfunction soften(budget: RateLimitConfig): RateLimitConfig {\n return budget.action === 'block' ? { ...budget, action: 'flag' } : budget;\n}\n\n/**\n * The rate limiter kernl hands to kehto's runtime: the guard profile's budget\n * for each operation class.\n *\n * The runtime charges what it is about to carry out, after kernl's own guard\n * let the envelope through: each request a service puts to the firewall, and\n * the storage, settings and applet-to-applet traffic the runtime serves\n * itself. That includes the envelopes kernl held for a hidden window and\n * released later, which meet the budget at the focus the window has then.\n * The configuration is read on every charge, so a profile change applies at\n * once and counters carry over. Where kehto only observes, because a protocol\n * has no way to refuse, a spent budget flags and never blocks. There is no\n * startup burst here: kernl's ingress guard counts every second of a window's\n * life, and the runtime's count of a first second starts when the window was\n * planned, not when it ran.\n *\n * @param config - The guard configuration in force, read on every charge.\n * @returns The limiter for `permissions.rateLimiter`.\n * @example\n * ```ts\n * const rateLimiter = createRuntimeRateLimiter(() => pipeline.config);\n * const permissions: PermissionAdapter = { ...approvals, rateLimiter };\n * ```\n */\nexport function createRuntimeRateLimiter(config: () => GuardConfig): TemporalPolicy {\n let state = createRateLimitState();\n return {\n evaluate(observation, mode = 'enforce') {\n if (SECOND_LEGS.has(observation.operation)) return { allowed: true, action: 'ignore', reason: 'within-budget' };\n const opClass = runtimeOpClass(observation.operation);\n const budget = config().rateLimits[opClass];\n const result = evaluateRateLimit(mode === 'observe' ? soften(budget) : budget, state, { ...observation, operation: opClass });\n state = result.state;\n return result;\n },\n retire(subject, lifecycle) {\n state = retireRateLimitLifecycle(state, subject, lifecycle);\n },\n };\n}\n\n/**\n * Turn a runtime budget event into a guard event. The runtime's event names\n * the window and the operation and carries nothing the applet sent. Reasons\n * follow the guard's vocabulary: a spent class budget is `rate:<class>`, and a\n * question the firewall did not put to the person because the applet asked\n * too often is `flood:prompts`.\n *\n * @param event - What the runtime reported through `permissions.onRateLimit`.\n * @param napplet - The applet the window runs, as the shell resolved it.\n * @param at - When it happened.\n * @returns The guard event.\n * @example\n * ```ts\n * toGuardEvent({ windowId: 'w1', operation: 'storage.set', action: 'block', reason: 'rate-exceeded' }, 'chat', 0).reason;\n * // 'rate:storage:write'\n * ```\n */\nexport function toGuardEvent(event: PermissionRateEvent, napplet: string, at: number): GuardEvent {\n const opClass = runtimeOpClass(event.operation);\n const reason = event.operation === 'permission.prompt' ? 'flood:prompts' : `rate:${opClass}`;\n return { disposition: event.action === 'block' ? 'reject' : 'flag', windowId: event.windowId, napplet, opClass, reason, at };\n}\n","import { BehaviorSubject, type Observable } from 'rxjs';\nimport {\n createPermissionRules,\n deserializePermissionRules,\n resolvePermissionRule,\n serializePermissionRules,\n setPermissionRule,\n type PermissionPrincipal,\n type PermissionRequest,\n type PermissionRequirement,\n type PermissionRuleAction,\n type PermissionRules,\n} from '@kehto/firewall';\nimport type { FirewallRuleTarget, StorageLike } from '../types.js';\n\n/**\n * Where the person's firewall rules are kept in the host storage.\n *\n * @example\n * ```ts\n * localStorage.getItem(FIREWALL_RULES_STORAGE_KEY); // kehto's serialised rules, once the person changed one\n * ```\n */\nexport const FIREWALL_RULES_STORAGE_KEY = 'kernl:firewall-rules:v1';\n\n/**\n * The rules a shell starts with: everything the person granted is allowed\n * without asking, and opening a link outside the shell asks every time.\n *\n * The grants layer already decided which domains an applet holds, so asking\n * again for each of them would bury the one question that matters under a\n * wall of prompts. A link leaves the shell, which no grant describes, so it is\n * the one request that always asks (D-056).\n *\n * @returns Fresh rules; change them with kehto's `setPermissionRule`.\n * @example\n * ```ts\n * const rules = defaultFirewallRules();\n * rules.default; // 'allow'\n * rules.operations['link.open']; // 'ask'\n * ```\n */\nexport function defaultFirewallRules(): PermissionRules {\n return createPermissionRules({ default: 'allow', operations: { 'link.open': 'ask' } });\n}\n\n/** The person's firewall rules, kept across visits. */\nexport interface FirewallRules {\n /** The rules in force. */\n current(): PermissionRules;\n readonly rules$: Observable<PermissionRules>;\n /**\n * Set one rule, or remove it with `undefined` so the next wider rule applies.\n * Throws `invalid:rule` for a target kehto refuses.\n */\n set(target: FirewallRuleTarget, action: PermissionRuleAction | undefined): void;\n /** Go back to {@link defaultFirewallRules}. */\n restoreDefaults(): void;\n /** What the rules say about a request no stored answer covers; kehto's `defaultDecision`. */\n decide(request: Pick<PermissionRequest, 'principal'>, missing: readonly PermissionRequirement[]): PermissionRuleAction;\n /** Whether the rules allow one requirement for one applet without asking. */\n allows(principal: PermissionPrincipal, requirement: PermissionRequirement): boolean;\n}\n\nfunction load(storage: StorageLike): PermissionRules {\n const raw = storage.getItem(FIREWALL_RULES_STORAGE_KEY);\n if (raw === null) return defaultFirewallRules();\n const loaded = deserializePermissionRules(raw);\n // A damaged document falls back to the shipped rules: it must never widen what is allowed.\n return loaded.ok ? loaded.rules : defaultFirewallRules();\n}\n\n/**\n * The firewall's rules over the host storage.\n *\n * A request no stored answer covers is decided by the most specific rule kehto\n * finds: the applet's rule for that request, for its domain, the applet's\n * default, then the same three for every applet. Any `deny` among a request's\n * requirements refuses it, any `ask` asks, and it is allowed without asking\n * only when every requirement is. Rules are keyed by an applet's catalogue id,\n * so they survive a new version; stored answers stay tied to the exact code.\n *\n * @param storage - The host storage; rules live under {@link FIREWALL_RULES_STORAGE_KEY}.\n * @returns The rules.\n * @example\n * ```ts\n * const rules = createFirewallRules(localStorage);\n * rules.set({ domain: 'relay' }, 'ask');\n * rules.set({ applet: summary.manifest.catalogId, operation: 'link.open' }, 'allow');\n * ```\n */\nexport function createFirewallRules(storage: StorageLike): FirewallRules {\n const rules$ = new BehaviorSubject<PermissionRules>(load(storage));\n const replace = (next: PermissionRules): void => {\n storage.setItem(FIREWALL_RULES_STORAGE_KEY, serializePermissionRules(next));\n rules$.next(next);\n };\n const allows = (principal: PermissionPrincipal, requirement: PermissionRequirement): boolean => resolvePermissionRule(rules$.value, principal, requirement) === 'allow';\n return {\n current: () => rules$.value,\n rules$: rules$.asObservable(),\n set(target, action) {\n const { applet, ...rest } = target;\n let next: PermissionRules;\n try {\n next = setPermissionRule(rules$.value, { ...rest, ...(applet === undefined ? {} : { napplet: applet }) }, action);\n } catch {\n throw new Error('invalid:rule');\n }\n replace(next);\n },\n restoreDefaults: () => replace(defaultFirewallRules()),\n decide(request, missing) {\n const actions = missing.map((requirement) => resolvePermissionRule(rules$.value, request.principal, requirement));\n if (actions.includes('deny')) return 'deny';\n return actions.every((action) => action === 'allow') ? 'allow' : 'ask';\n },\n allows,\n };\n}\n","import type { PermissionAdmission, Runtime } from '@kehto/runtime';\nimport type { ShellEnvironment } from '@kehto/shell';\nimport type { AppletSummary } from '../types.js';\nimport { permissionPrincipalFor } from './permissions.js';\n\n/**\n * How many planned windows may wait to be mounted. A host that plans and never\n * mounts would otherwise leave a session behind for each; past this, the\n * oldest plan is dropped and mounting it fails with `denied:admission-expired`.\n *\n * @example\n * ```ts\n * MAX_UNMOUNTED_PLANS; // 16\n * ```\n */\nexport const MAX_UNMOUNTED_PLANS = 16;\n\n/** What admission needs from kehto's runtime. */\nexport type AdmissionRuntime = Pick<Runtime, 'sessionRegistry' | 'permissions' | 'destroyWindow'>;\n\n/** The firewall's say over which applets start, and with which domains. */\nexport interface AppletAdmissions {\n /**\n * Put an applet's start to the firewall, before any of its code runs.\n * Resolves the domains it starts with; `shell` is always among them when offered.\n * Throws `denied:firewall` when a domain the applet requires was refused,\n * and `unavailable:firewall` when the firewall could not decide.\n */\n admit(windowId: string, summary: AppletSummary, environment: ShellEnvironment): Promise<readonly string[]>;\n /** Whether the window's admission still stands: nothing it was admitted under was taken back. */\n isCurrent(windowId: string): boolean;\n /** The window was mounted, so it no longer counts as waiting. */\n mounted(windowId: string): void;\n /** Forget a window and end the session admission opened for it. */\n discard(windowId: string): void;\n /** Call `listener` whenever an answer is taken back; returns the unsubscribe. */\n onInvalidated(listener: () => void): () => void;\n /** Discard every window still waiting to be mounted. */\n close(): void;\n}\n\nfunction failure(status: Exclude<PermissionAdmission['status'], 'admitted'>): Error {\n return new Error(status === 'denied' || status === 'cancelled' ? 'denied:firewall' : 'unavailable:firewall');\n}\n\n/**\n * Admit applets through kehto's firewall before they run.\n *\n * kehto dispatches nothing for a window whose session holds no admission, so\n * kernl opens the session itself when it plans the window, under the verified\n * principal, and asks the firewall for every domain the grants layer left the\n * applet. Domains the applet requires are decided together and refuse the\n * start when refused; each other domain is decided on its own and is simply\n * left out when refused. With kernl's shipped rules none of this asks the\n * person anything. `shell` is the read-only control plane and is not a\n * permission, as in kehto's own launcher.\n *\n * @param runtime - kehto's runtime, with `permissions` configured.\n * @param now - Clock for the session's registration time.\n * @returns The admissions.\n * @example\n * ```ts\n * const admissions = createAppletAdmissions(bridge.runtime, Date.now);\n * const domains = await admissions.admit('applet-1', summary, environment);\n * if (admissions.isCurrent('applet-1')) frame.srcdoc = srcdoc;\n * ```\n */\nexport function createAppletAdmissions(runtime: AdmissionRuntime, now: () => number): AppletAdmissions {\n const admitted = new Map<string, PermissionAdmission>();\n const waiting = new Set<string>();\n const permissions = (): NonNullable<Runtime['permissions']> => {\n if (!runtime.permissions) throw new Error('unavailable:firewall');\n return runtime.permissions;\n };\n const discard = (windowId: string): void => {\n admitted.delete(windowId);\n waiting.delete(windowId);\n runtime.destroyWindow(windowId);\n runtime.sessionRegistry.unregister(windowId);\n };\n return {\n async admit(windowId, summary, environment) {\n const { identity } = summary;\n const firewall = permissions();\n runtime.sessionRegistry.register(windowId, {\n pubkey: '',\n windowId,\n origin: 'null',\n type: 'nip5d',\n dTag: identity.dTag,\n aggregateHash: identity.hash,\n permissionPrincipal: permissionPrincipalFor(summary),\n registeredAt: now(),\n instanceId: crypto.randomUUID(),\n provenance: 'nip-5d',\n });\n const available = environment.capabilities.domains;\n const asked = available.filter((domain) => domain !== 'shell');\n const required = asked.filter((domain) => summary.requires.includes(domain));\n const optional = asked.filter((domain) => !required.includes(domain));\n const admission = await firewall.admit(windowId, { available, required, optional });\n if (admission.status !== 'admitted') {\n discard(windowId);\n throw failure(admission.status);\n }\n admitted.set(windowId, admission);\n waiting.add(windowId);\n for (const oldest of [...waiting].slice(0, Math.max(0, waiting.size - MAX_UNMOUNTED_PLANS))) discard(oldest);\n return available.filter((domain) => domain === 'shell' || admission.domains.includes(domain));\n },\n isCurrent(windowId) {\n const admission = admitted.get(windowId);\n return admission !== undefined && permissions().isAdmissionCurrent(windowId, admission);\n },\n mounted: (windowId) => void waiting.delete(windowId),\n discard,\n onInvalidated: (listener) => permissions().subscribeInvalidation(listener),\n close() {\n for (const windowId of waiting) discard(windowId);\n },\n };\n}\n","import { Subject, map, startWith, type Observable } from 'rxjs';\nimport { DEFAULT_RULE_GRANT_PREFIX, type PermissionGrant, type RuntimePermissions } from '@kehto/runtime';\nimport type { Firewall, FirewallDecision } from '../types.js';\nimport type { FirewallRules } from './rules.js';\n\n/** Options for {@link createFirewall}. */\nexport interface FirewallOptions {\n readonly rules: FirewallRules;\n /** kehto's grant store, from `bridge.runtime.permissions`. */\n readonly permissions: RuntimePermissions;\n}\n\n/** The firewall surface plus the hook the shell calls when the person answered a question. */\nexport interface KernlFirewall extends Firewall {\n /** Tell `decisions$` the answers may have changed. */\n touch(): void;\n close(): void;\n}\n\nfunction toDecision(grant: PermissionGrant): FirewallDecision | undefined {\n // A `once` answer is used up by the request it was given for; it is never in force afterwards.\n if (grant.lifetime === 'once' || grant.principal.kind !== 'verified') return undefined;\n const { permission } = grant;\n const kind = permission.category === 'interface' ? 'access' : permission.category === 'network' ? 'network' : 'resource';\n return {\n id: grant.id,\n catalogId: grant.principal.manifestKey,\n hash: grant.principal.artifactHash,\n request: { kind, domain: permission.domain, operation: permission.operation, target: permission.scope.value },\n effect: grant.effect,\n lifetime: grant.lifetime === 'persistent' ? 'always' : 'session',\n byRule: grant.id.startsWith(DEFAULT_RULE_GRANT_PREFIX),\n };\n}\n\n/**\n * The firewall as the host sees it: the rules, and the answers in force.\n *\n * Changing a rule takes back every answer the rules gave that they no longer\n * give, as kehto requires of a host, so a tightened rule applies to applets\n * already running: kehto ends the work those answers covered and kernl stops\n * the window (see `createAppletLifecycle`). Answers the person gave stay until\n * they take them back.\n *\n * @param options - The rules and kehto's grant store.\n * @returns The firewall.\n * @example\n * ```ts\n * const firewall = createFirewall({ rules, permissions: bridge.runtime.permissions });\n * firewall.setRule({ domain: 'relay' }, 'ask');\n * firewall.decisions().filter((decision) => !decision.byRule);\n * ```\n */\nexport function createFirewall(options: FirewallOptions): KernlFirewall {\n const { rules, permissions } = options;\n const touched$ = new Subject<void>();\n const decisions = (): readonly FirewallDecision[] => permissions.grants.flatMap((grant) => toDecision(grant) ?? []);\n const stopFollowing = permissions.subscribeInvalidation(() => touched$.next());\n const retractRuleAnswers = (): void => {\n const stale = permissions.grants.filter((grant) => grant.id.startsWith(DEFAULT_RULE_GRANT_PREFIX) && !rules.allows(grant.principal, grant.permission));\n for (const grant of stale) permissions.revoke(grant.id);\n };\n return {\n rules: () => rules.current(),\n rules$: rules.rules$,\n setRule(target, action) {\n rules.set(target, action);\n retractRuleAnswers();\n },\n restoreDefaults() {\n rules.restoreDefaults();\n retractRuleAnswers();\n },\n get available() {\n return permissions.available;\n },\n decisions,\n decisions$: touched$.pipe(startWith(undefined), map(decisions)) as Observable<readonly FirewallDecision[]>,\n forget: (id) => permissions.revoke(id),\n forgetAll: () => permissions.clear(),\n touch: () => touched$.next(),\n close() {\n stopFollowing();\n touched$.complete();\n },\n };\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 } from './domain-capabilities.js';\nimport { capabilitiesInForce, domainsInForce, withheldDomains } from './message-isolation.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. An applet that holds messages is sealed: only the domains that\n * cannot send what it read anywhere stay in force, and the rest are reported\n * as `withheld` (D-046). 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: capabilitiesInForce(entry.domains),\n withheld: withheldDomains(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>(capabilitiesInForce(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. An\n * applet that holds messages sees only the domains that may go with them.\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'] : domainsInForce(record?.domains ?? [], grants.baselineDomains()));\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 RELAY_ADDRESS = /^wss?:\\/\\//i;\nconst RELAY_TAGS = new Set(['r', 'relay', 'relays']);\nconst TYPE_TAGS = new Set(['k', 'kind']);\n\n/** A relay as the person reads it: its own host and path, without the scheme or a trailing slash. Nothing else is dropped (D-051). */\nfunction relayName(address: string): string {\n return address.replace(RELAY_ADDRESS, '').replace(/\\/+$/, '');\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 (RELAY_TAGS.has(name) || RELAY_ADDRESS.test(value)) return `relay ${relayName(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(relayName);\n const inbox = changeLines(names(before ? getInboxes(before) : []), names(getInboxes(event)), 'Inbox relays', (item) => item);\n const outbox = changeLines(names(before ? getOutboxes(before) : []), names(getOutboxes(event)), 'Outbox relays', (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 identity has published' }];\n lines.push({ label: 'Relays asked', after: everywhere ? 'Every relay' : describeItems(services, relayName) });\n return destructive(event, applet, 'Ask relays to erase your identity', 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 createBlossomBridge,\n createBridgeRegistry,\n createHandoffBackends,\n createHttpBridge,\n createMailBridge,\n createNzbBridge,\n createSoulseekBridge,\n createTorrentBridge,\n type BlossomBridgeOptions,\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 /** The servers to look for a `blossom:` blob on for each requester, after the reference's own hints (D-055). */\n readonly blossomServers?: BlossomBridgeOptions['serversFor'];\n}\n\n/**\n * The shell's bridge registry: the web bridge, complete, the Blossom bridge, which\n * fetches through the same web policy and verifies every blob's hash (D-055), plus\n * the downloads, sharing 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 * createDefaultBridges({ blossomServers: (requester) => serversOf(requester) }).forScheme('blossom')?.id; // 'blossom'\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, blossomServers, ...registryOptions } = options;\n const registry = createBridgeRegistry(registryOptions);\n const backends = handoff ? createHandoffBackends(handoff) : undefined;\n registry.register(createHttpBridge(http));\n registry.register(createBlossomBridge({ ...(http ? { http } : {}), ...(blossomServers ? { serversFor: blossomServers } : {}) }));\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' | 'getPublicKey'> | 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 // Under the firewall kehto has the destination approved before any byte leaves. The plan names the\n // first file server, where the file goes first; the mirrors are the person's own list (D-033).\n async planUpload(request, ctx) {\n const signer = options.signer();\n if (!signer) throw new Error('denied:read-only');\n const [destination] = await options.servers();\n if (destination === undefined) throw new Error('unavailable:no-file-server');\n return { rail: 'blossom', destination, signingPubkey: await signer.getPublicKey(), execute: () => this.upload(request, ctx) };\n },\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, 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 /** Reads a person from any form of their identity, asking the servers it names first; `invalid:person` otherwise. */\n readonly locate: (input: string) => Promise<string>;\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\nconst located = (options: CommonActionsOptions, value: string): Promise<string | undefined> => options.locate(value).catch(() => undefined);\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 = await Promise.all(pubkeys.map((key) => located(options, key)));\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 = await located(options, 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 { createPeople, type People } from './people/person.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 people: People;\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 people = createPeople({ store: eventStore, pool });\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, people, 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' | 'people' | 'replaceableLoader' | 'signer'>, consent: SigningConsent): CommonServiceOptions {\n const { eventStore, pool, tiers, accounts } = parts;\n return createCommonActions({\n store: eventStore,\n profiles: network.profiles,\n locate: network.people.locate,\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, EMPTY, lastValueFrom, takeUntil, tap, timer } from 'rxjs';\nimport type { EventStore } from 'applesauce-core';\nimport { decodePointer } from 'applesauce-core/helpers';\nimport type { NostrEvent } from '@napplet/core';\nimport { asFilters, type ApplesaucePool } from '../applesauce/relay-hooks.js';\n\n/** A person, and where whoever shared them said their data is kept. */\nexport interface PersonPointer {\n /** The identity, as 64 lowercase hex characters. */\n readonly pubkey: string;\n /** Servers named alongside the identity; empty when none were. */\n readonly relays: readonly string[];\n}\n\nconst URI_SCHEME = /^nostr:/i;\nconst SOCKET_URL = /^wss?:\\/\\//i;\nconst HEX_KEY = /^[0-9a-f]{64}$/;\nconst NO_RELAYS: readonly string[] = Object.freeze([]);\n\nfunction decodeOrNothing(text: string): ReturnType<typeof decodePointer> | undefined {\n try {\n return decodePointer(text);\n } catch {\n return undefined;\n }\n}\n\n/**\n * The longest the hinted servers are waited for before a lookup goes on\n * without them. An outer bound only: it ends as soon as they have all answered.\n *\n * @example\n * ```ts\n * createPeople({ store, pool, timeoutMs: PERSON_HINT_TIMEOUT_MS });\n * ```\n */\nexport const PERSON_HINT_TIMEOUT_MS = 8_000;\n\n/** What says who a person is and where they read and are written to: profile, server list, message inboxes. */\nconst PERSON_KINDS = [0, 10002, 10050];\n\n/**\n * Read an identity out of what someone typed, pasted or was sent.\n *\n * Every NIP-19 form of a person is one: 64 hex characters, an `npub`, or an\n * `nprofile`, with or without a `nostr:` prefix and in any case. An\n * `nprofile` carries the servers its data is on, which come back as `relays`.\n *\n * @param input - The text.\n * @returns The person, or `undefined` when the text is none of those.\n * @example\n * ```ts\n * parsePerson('npub1…'); // { pubkey: '3bf0…', relays: [] }\n * parsePerson('nostr:nprofile1…'); // { pubkey: '3bf0…', relays: ['wss://relay.example'] }\n * parsePerson('hello'); // undefined\n * ```\n */\nexport function parsePerson(input: string): PersonPointer | undefined {\n const text = input.trim().replace(URI_SCHEME, '').toLowerCase();\n if (HEX_KEY.test(text)) return Object.freeze({ pubkey: text, relays: NO_RELAYS });\n const decoded = decodeOrNothing(text);\n if (decoded?.type === 'npub') return Object.freeze({ pubkey: decoded.data, relays: NO_RELAYS });\n // An address of anything else, or a secret key, is not a person, whatever key it happens to hold.\n if (decoded?.type !== 'nprofile') return undefined;\n // The decoder always gives an nprofile its list of servers, empty when it names none; only the type says otherwise.\n const named = decoded.data.relays as readonly string[];\n return Object.freeze({ pubkey: decoded.data.pubkey, relays: Object.freeze(named.filter((url) => SOCKET_URL.test(url))) });\n}\n\n/** Options for {@link createPeople}. */\nexport interface PeopleOptions {\n /** The shell's event store; what the hinted servers hold is put here, where every lookup reads first. */\n readonly store: EventStore;\n readonly pool: ApplesaucePool;\n /** Outer bound on waiting for the hinted servers; {@link PERSON_HINT_TIMEOUT_MS} by default. */\n readonly timeoutMs?: number;\n}\n\n/** Finds people from any form of their identity. */\nexport interface People {\n /** Read an identity; `undefined` when the text is not one. Asks nobody. */\n parse(input: string): PersonPointer | undefined;\n /**\n * Read an identity and, when it names servers, fetch the person's profile,\n * server list and message inboxes from them first, so whatever looks the\n * person up next finds them.\n *\n * @throws `invalid:person` when the text is not an identity.\n */\n locate(input: string): Promise<string>;\n}\n\n/**\n * Create the shell's way of finding a person from what was typed or sent.\n *\n * The servers an `nprofile` names are asked once per person and set of\n * servers, and what they hold is added to the shell's event store. A server\n * that fails or says nothing costs nothing: the lookup goes on with the\n * shell's own servers, as it would have without the hint.\n *\n * @param options - The event store, the pool and the outer bound.\n * @returns The finder.\n * @example\n * ```ts\n * const people = createPeople({ store: eventStore, pool });\n * const pubkey = await people.locate('nprofile1…');\n * ```\n */\nexport function createPeople(options: PeopleOptions): People {\n const asked = new Map<string, Promise<void>>();\n\n const ask = (person: PersonPointer): Promise<void> => {\n const key = `${person.pubkey}:${[...person.relays].sort().join(',')}`;\n const known = asked.get(key);\n if (known) return known;\n const done = lastValueFrom(\n options.pool.request([...person.relays], asFilters([{ kinds: PERSON_KINDS, authors: [person.pubkey] }])).pipe(\n takeUntil(timer(options.timeoutMs ?? PERSON_HINT_TIMEOUT_MS)),\n tap((event: NostrEvent) => options.store.add(event)),\n catchError(() => EMPTY),\n ),\n { defaultValue: undefined },\n ).then(() => undefined);\n asked.set(key, done);\n return done;\n };\n\n return {\n parse: parsePerson,\n async locate(input) {\n const person = parsePerson(input);\n if (!person) throw new Error('invalid:person');\n if (person.relays.length > 0) await ask(person);\n return person.pubkey;\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 type { ServiceHandler } from '@kehto/runtime';\nimport { createKeysService } from '@kehto/services';\n\n/** A key press, as the page's `KeyboardEvent` names its parts. */\nexport interface ShortcutKey {\n readonly key: string;\n readonly code: string;\n readonly ctrlKey: boolean;\n readonly altKey: boolean;\n readonly shiftKey: boolean;\n readonly metaKey: boolean;\n}\n\n/** The host's settings for applets' keyboard shortcuts. */\nexport interface ShortcutSettings {\n /** Chords the shell keeps for itself, such as `'Alt+/'`; an applet asking for one is answered without a binding. */\n readonly reserved?: readonly string[];\n /** Where key presses outside applets are heard; the page's `document` by default, and nowhere when there is none. */\n readonly target?: EventTarget;\n}\n\n/** Options for {@link createShortcutsService}. */\nexport interface ShortcutsOptions extends ShortcutSettings {\n /** Whether a window is the focused one, as the shell's window manager reports it. */\n readonly isFocused: (windowId: string) => boolean;\n}\n\n/** The `keys` service, with the listener it must give back. */\nexport type ShortcutsService = ServiceHandler & { destroy(): void };\n\n/** What the service reads from a `keydown` on the shell's own page. */\ninterface PagePress extends ShortcutKey {\n readonly repeat?: boolean;\n readonly isComposing?: boolean;\n readonly defaultPrevented?: boolean;\n readonly target: object;\n}\n\n/** Elements that take a key press for themselves: typing, choosing, pressing. */\nconst CONTROL_TAGS: ReadonlySet<string> = new Set(['INPUT', 'TEXTAREA', 'SELECT', 'BUTTON', 'A', 'SUMMARY']);\n\n/** While a listener runs, an event's target is the object it was dispatched on, never null. */\nfunction isControl(target: object): boolean {\n const { tagName, isContentEditable } = target as { tagName?: unknown; isContentEditable?: unknown };\n return isContentEditable === true || (typeof tagName === 'string' && CONTROL_TAGS.has(tagName.toUpperCase()));\n}\n\n/** A key press on the shell's page that is the shell's own business: handled, being composed, or aimed at a control. */\nfunction isShellsOwn(press: PagePress): boolean {\n return press.defaultPrevented === true || press.isComposing === true || isControl(press.target);\n}\n\nfunction pageTarget(options: ShortcutSettings): EventTarget | undefined {\n return options.target ?? (typeof document === 'undefined' ? undefined : document);\n}\n\n/**\n * The `keys` domain (D-054): kehto's reference service, which binds the key an\n * applet asks for, tells it which keys it holds and runs its action when the\n * key is pressed outside every applet, behind three rules of kernl's. A key\n * pressed on the shell's own page reaches applets only when the shell did not\n * use it: not one it handled, and not one typed into a field or pressed on a\n * button. The action runs in the focused window only, where kehto would run it\n * in every window that bound the key, so two windows of one applet do not both\n * act. And a key that ran an action does nothing else on the page. A key\n * pressed inside an applet never comes through here: the frame knows its own\n * bindings and runs the action itself.\n *\n * @param options - Reserved chords, where keys are heard and the focus source.\n * @returns The service for the registry; call `destroy()` to stop listening.\n * @example\n * ```ts\n * registry.keys = createShortcutsService({ reserved: ['Alt+/'], isFocused: (windowId) => wm.isFocused(windowId) });\n * ```\n */\nexport function createShortcutsService(options: ShortcutsOptions): ShortcutsService {\n // kehto listens here, not on the page, so only the presses kernl lets through reach it.\n const relayed = new EventTarget();\n const service = createKeysService({ listenerTarget: relayed, ...(options.reserved ? { reservedChords: options.reserved } : {}) });\n const page = pageTarget(options);\n let acted = false;\n\n const onKeydown = (event: Event): void => {\n const press = event as Event & PagePress;\n if (isShellsOwn(press)) return;\n const { key, code, ctrlKey, altKey, shiftKey, metaKey } = press;\n acted = false;\n relayed.dispatchEvent(Object.assign(new Event('keydown'), { key, code, ctrlKey, altKey, shiftKey, metaKey, repeat: press.repeat }));\n if (acted) event.preventDefault();\n };\n page?.addEventListener('keydown', onKeydown);\n\n return {\n ...service,\n handleMessage(windowId, message, send) {\n // kehto keeps this `send` for the window's later pushes, so the focus check rides on it.\n service.handleMessage(windowId, message, (reply) => {\n if (reply.type !== 'keys.action') return send(reply);\n if (!options.isFocused(windowId)) return;\n acted = true;\n send(reply);\n });\n },\n destroy() {\n page?.removeEventListener('keydown', onKeydown);\n service.destroy();\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 identity' },\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 ResourceServiceError,\n createThemeService,\n createUploadService,\n type CommonServiceOptions,\n type ConfigServiceOptions,\n type DmService,\n type OutboxPublishResult,\n type OutboxRouter,\n type RelayListEntry,\n type ResourceErrorCode,\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 { createShortcutsService, type ShortcutsOptions, type ShortcutsService } from './keys/shortcuts.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 { locateRecipients, locateSendRecipients } from './people/locate-recipients.js';\nimport type { People } from './people/person.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 /** Reads the people an applet names in any form of their identity; without it only hex is taken. */\n readonly people?: Pick<People, 'locate'>;\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 /** Reserved chords, the key listener's target and the focus source for the `keys` domain (D-054). */\n readonly shortcuts: ShortcutsOptions;\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 /** The `keys` service; `destroy()` gives back its key listener. */\n readonly keys: ShortcutsService;\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 const accept = (result: OutboxPublishResult): OutboxPublishResult => {\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 // Under the firewall kehto plans a publish, has the plan approved and publishes through `publishWithPlan`, so that path gets the same policy.\n const planned = router as PlannedPublishRouter;\n const publishWithPlan = planned.publishWithPlan?.bind(planned);\n return {\n ...router,\n publish: async (template, options) => accept(await router.publish(template, options)),\n ...(publishWithPlan ? { publishWithPlan: async (...args: Parameters<typeof publishWithPlan>) => accept(await publishWithPlan(...args)) } : {}),\n } as OutboxRouter;\n}\n\n/** The planned publish kehto's relay-pool router adds beside `OutboxRouter`; kehto does not export its type. */\ninterface PlannedPublishRouter extends OutboxRouter {\n publishWithPlan?(template: EventTemplate, plan: unknown): Promise<OutboxPublishResult>;\n}\n\n/**\n * The relays the shell itself may reach for an applet, as bare origins: the\n * form kehto's firewall takes a network destination in.\n *\n * kehto's messaging and social services have each request's relays approved\n * before they run it. In kernl the applet never chooses them: a provider finds\n * the recipient's inboxes and a post goes to the tier for its kind, so the\n * plan is every relay in the shell's tiers, which is the widest set either can\n * reach. A relay whose address is not a bare `ws:` or `wss:` origin is left out.\n *\n * @param tiers - The shell's relay tiers.\n * @returns Distinct relay origins.\n * @example\n * ```ts\n * shellRelayOrigins(tiers); // ['wss://relay.example', …]\n * ```\n */\nexport function shellRelayOrigins(tiers: Pick<RelayTiers, 'get'>): readonly string[] {\n const { outbox, discovery, apps, super: shared } = tiers.get();\n const origins = [...outbox, ...shared, ...discovery, ...apps].flatMap((relay) => {\n const origin = /^(wss?:\\/\\/[^/?#@]+)\\/?$/.exec(relay)?.[1];\n return origin ? [origin] : [];\n });\n return [...new Set(origins)];\n}\n\n/**\n * Have the firewall approve the server a download contacts before it is\n * contacted. kehto's resource service passes `authorizeNetwork` when the\n * firewall is on; a web address is put to it by origin, and anything else\n * (a magnet link, a file-server address) is resolved by its bridge, which\n * names its own servers. Upstream gap: the bridge registry follows a redirect\n * itself under its own address policy, so only the first origin is put to the\n * firewall.\n *\n * @param url - The address the applet asked for.\n * @param init - What kehto's resource service passed.\n * @param run - Resolves the address under the signal it is given.\n * @returns What `run` resolved.\n * @example\n * ```ts\n * createResourceService({ fetch: (url, init) => fetchThroughFirewall(url, init, (signal) => resolve(url, { signal })) });\n * ```\n */\nexport function fetchThroughFirewall<T>(url: string, init: Pick<ResourceFetchInit, 'signal' | 'authorizeNetwork'>, run: (signal: AbortSignal) => Promise<T>): Promise<T> {\n return init.authorizeNetwork && /^https?:/i.test(url) ? init.authorizeNetwork(url, run) : run(init.signal);\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/** NAP-RESOURCE codes for the bridges' reasons, most specific first; the rest of a family takes its prefix's code. */\nconst RESOURCE_CODES: readonly (readonly [prefix: string, code: ResourceErrorCode])[] = [\n ['unavailable:no-bridge', 'unsupported-scheme'],\n ['unavailable:not-found', 'not-found'],\n ['unavailable:no-servers', 'not-found'],\n ['unavailable:timeout', 'timeout'],\n ['denied:too-large', 'too-large'],\n ['invalid:', 'invalid-request'],\n ['denied:', 'blocked-by-policy'],\n];\n\n/**\n * The NAP-RESOURCE error a bridge failure becomes. The bridges reject with\n * prefixed reasons; kehto's resource service reports any error that is not a\n * `ResourceServiceError` as `network-error`, so without this an applet could\n * not tell a missing blob or an unsupported scheme from a dead network (D-055).\n *\n * @param error - What the bridge registry rejected with.\n * @returns The error to throw to the resource service, carrying the bridge's reason as its message.\n * @example\n * ```ts\n * resourceErrorFor(new Error('unavailable:not-found')).code; // 'not-found'\n * resourceErrorFor(new Error('unavailable:network Failed to fetch')).code; // 'network-error'\n * ```\n */\nexport function resourceErrorFor(error: unknown): ResourceServiceError {\n const reason = error instanceof Error ? error.message : String(error);\n const code = RESOURCE_CODES.find(([prefix]) => reason.startsWith(prefix))?.[1] ?? 'network-error';\n return new ResourceServiceError(code, reason);\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`, `keys`, `notify`, `link`, `resource`, `dm`,\n * `outbox` 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. An applet's shortcut runs in the focused\n * window only.\n *\n * @param deps - Pool, tiers, store, auth, consent gate, host, registries and identity resolver.\n * @returns The service registry and the theme, dm and keys 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 located = deps.people ? locateRecipients(deps.messaging.composite(), deps.people) : deps.messaging.composite();\n const relayPlan = (): readonly string[] => shellRelayOrigins(deps.tiers);\n const labelled = deps.profiles ? labelConversations(located, deps.profiles) : located;\n const dmService = createDmService({ adapter: { ...labelled, planRelays: relayPlan } });\n const dm = deps.people ? locateSendRecipients(dmService, deps.people) : dmService;\n const resolve = createBridgeResourceResolver(deps.bridges);\n const identities = deps.identities ?? createWindowIdentities();\n const direct = deps.directConnections;\n const chosen = () => deps.multiplayer?.state();\n const keys = createShortcutsService(deps.shortcuts);\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 keys,\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 // kehto calls this only after the firewall let this exact link through, so the host need not ask again (D-056).\n open: ({ url }) => {\n deps.host.openLink(url.href, { approved: true });\n return { status: 'opened' };\n },\n }),\n // The firewall approves a web address's server before it is contacted (D-056); a bridge's reason becomes a NAP-RESOURCE code (D-055).\n resource: createResourceService({\n fetch: (url, init) =>\n fetchThroughFirewall(url, init, (signal) => resolve(url, resourceInitFor(deps, { ...init, signal }))).catch((error: unknown) => {\n throw resourceErrorFor(error);\n }),\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({ planRelays: relayPlan, ...deps.common }) } : {}),\n ...(deps.uploader ? { upload: createUploadService({ uploader: deps.uploader, uploadInfo: { rails: [{ rail: 'blossom', enabled: true }] } }) } : {}),\n };\n return { registry, theme, dm, keys };\n}\n","import type { DmAdapter, DmService } from '@kehto/services';\nimport type { People } from './person.js';\n\n/**\n * Let an applet name the people it writes to in any form of their identity.\n *\n * Every recipient of a send is read with `people.locate`, so hex, `npub` and\n * `nprofile` all work and the servers an `nprofile` names are asked for the\n * person's inboxes before the message is sealed. The backends still see hex.\n *\n * @param adapter - The messaging adapter to wrap.\n * @param people - The shell's finder.\n * @returns The adapter, with recipients read on the way in.\n * @throws `invalid:recipient` from `send` when a recipient is not an identity.\n * @example\n * ```ts\n * createDmService({ adapter: locateRecipients(messaging.composite(), kernl.people) });\n * ```\n */\nexport function locateRecipients(adapter: DmAdapter, people: Pick<People, 'locate'>): DmAdapter {\n return {\n ...adapter,\n async send(request) {\n const recipients = await Promise.all(request.recipients.map((recipient) => people.locate(recipient))).catch(() => {\n throw new Error('invalid:recipient');\n });\n return adapter.send({ ...request, recipients });\n },\n };\n}\n\n/**\n * Read the recipients of a send before kehto's service sees them.\n *\n * Under the firewall kehto has every recipient approved before a message is\n * sent, and takes them as hex keys only, so an `npub` or `nprofile` would be\n * refused before {@link locateRecipients} could read it. This reads them\n * first; every other request passes straight through.\n *\n * @param service - kehto's `dm` service.\n * @param people - The shell's finder.\n * @returns The service, with a send's recipients read on the way in.\n * @example\n * ```ts\n * registry.dm = locateSendRecipients(createDmService({ adapter }), kernl.people);\n * ```\n */\nexport function locateSendRecipients(service: DmService, people: Pick<People, 'locate'>): DmService {\n return {\n ...service,\n handleMessage(windowId, message, send) {\n const { id, recipients } = message as { id?: string; recipients?: unknown };\n if (message.type !== 'dm.send' || !Array.isArray(recipients)) {\n service.handleMessage(windowId, message, send);\n return;\n }\n Promise.all(recipients.map((recipient: string) => people.locate(recipient))).then(\n (located) => service.handleMessage(windowId, { ...message, recipients: located } as typeof message, send),\n () => send({ type: 'dm.send.result', id: id ?? '', error: 'invalid:recipient' } as typeof message),\n );\n },\n };\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 { PermissionAdapter, 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 { ShortcutKey } from './keys/shortcuts.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 firewall's host side: rules, questions, stored answers and the runtime's rate limiter; see `createFirewallPermissions`. */\n readonly permissions: PermissionAdapter;\n readonly onUnroutedMessage?: (info: UnroutedMessageInfo) => void;\n /** Hears every envelope on a bound port before the guard decides it; observe-only. */\n readonly onNappletMessage?: NonNullable<ShellAdapter['onNappletMessage']>;\n /** Takes a key an applet had no shortcut for, so the shell's own shortcuts work while an applet has focus (D-054). */\n readonly onShortcut?: (key: ShortcutKey) => 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; a key an\n * applet had no shortcut for goes to the host's `onShortcut`; 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 * under `permissions` that is a ceiling no firewall answer can exceed; every\n * request is decided by the firewall; and every port envelope passes kernl's\n * 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: (key) => deps.onShortcut?.(key) },\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 permissions: deps.permissions,\n aclDefaultPolicy: 'restrictive',\n ...(deps.onUnroutedMessage ? { onUnroutedMessage: deps.onUnroutedMessage } : {}),\n ...(deps.onNappletMessage ? { onNappletMessage: deps.onNappletMessage } : {}),\n };\n}\n","import type { Subscription } from 'rxjs';\nimport { originRegistry, type ShellAdapter, type ShellBridge, type ShellEnvironment } 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, resolveAppletEnvironment, type PlannedExtensions } from './applets/plan.js';\nimport { mountApplet, type MountedApplet } from './applets/mount.js';\nimport type { GuardPipeline, WindowResolution } from './guard/pipeline.js';\nimport type { AppletAdmissions } from './firewall/admission.js';\nimport { createEnvironmentResolver, 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 firewall's say over which applets start; planning asks it and mounting checks the answer still stands. */\n readonly admissions: AppletAdmissions;\n /** Tells the firewall which applet a window id's questions are about. */\n readonly remember: (summary: AppletSummary) => void;\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 /** Domains kernl serves beyond kehto's list, and their bindings; `domains` here is everything offered, before grants. */\n readonly extensions?: PlannedExtensions;\n}\n\n/** The offered extension domains this applet holds: the same grants rule as every other domain, blocked and sealed applets included. */\nfunction heldExtensions(context: LifecycleContext, identity: AppletIdentity): PlannedExtensions | undefined {\n const { extensions } = context;\n if (!extensions) return undefined;\n const held = createEnvironmentResolver(context.grants)({ dTag: identity.dTag, aggregateHash: identity.hash }, { domains: extensions.domains, services: [] });\n return { domains: held.domains, bindings: extensions.bindings };\n}\n\n/** The environment the firewall is asked about: kehto's domains and the extension domains the grants leave the applet. */\nfunction withExtensions(environment: ShellEnvironment, extensions: PlannedExtensions | undefined): ShellEnvironment {\n if (!extensions) return environment;\n return { ...environment, capabilities: { ...environment.capabilities, domains: [...environment.capabilities.domains, ...extensions.domains] } };\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. The one grant that\n * narrows is messages: it withholds every domain that could send them on, so\n * a window started with one of those stops (D-046).\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].filter((domain) => !record.withheld.includes(domain)));\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, puts the start to the firewall 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, admissions } = context;\n // An answer was taken back: a window admitted under it stops, as when a grant it used is taken back (D-038).\n const stopStale = (): void => {\n for (const handle of handles.values()) {\n if (admissions.isCurrent(handle.windowId)) continue;\n handle.revoked('firewall');\n bridge.revokeNapplet(handle.windowId, 'host');\n }\n };\n // kehto is still ending the work the answer covered when it tells us, so the windows stop right after it.\n const stopFollowing = admissions.onInvalidated(() => queueMicrotask(stopStale));\n context.subscriptions.add(() => {\n stopFollowing();\n admissions.close();\n });\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 const windowId = `applet-${windowCounter}`;\n context.remember(summary);\n const extensions = heldExtensions(context, summary.identity);\n // The firewall admits the applet before a plan exists, so no code runs with a domain it refused (D-056).\n const domains = await admissions.admit(windowId, summary, withExtensions(resolveAppletEnvironment(context.adapter, summary), extensions));\n const admitted = extensions && { ...extensions, domains: extensions.domains.filter((domain) => domains.includes(domain)) };\n return planMount({ summary, indexHtml, adapter: context.adapter, guardProfile: pipeline.config.profile, windowId, domains, ...(admitted ? { extensions: admitted } : {}) });\n },\n mount(plan: MountPlan, frame: FrameLike): AppletHandle {\n if (!admissions.isCurrent(plan.windowId)) throw new Error('denied:admission-expired');\n admissions.mounted(plan.windowId);\n const handle = mountApplet(plan, frame, {\n bridge,\n originRegistry,\n guard: pipeline,\n onRevoked: (windowId, reason, details) => context.host.onRevoked(windowId, reason, details),\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 // A window closed before it said hello has only the session admission opened for it.\n admissions.discard(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 type { BridgeContext } from '@kernlize/bridges';\nimport { buildShellCapabilities, createShellBridge, type ShellAdapter, type ShellBridge } from '@kehto/shell';\nimport { QUARANTINE_WINDOW_MS, createGuardConfig, describeMitigations, type GuardConfig, type GuardEvent } from '@kernlize/guard';\nimport type { AccountFileServers } from './files/file-servers.js';\nimport type { AppletIdentity, AppletStopLimit, AppletSummary, Grants, GuardFacade, Kernl, KernlHost, KernlMultiplayer, KernlOptions, RelayTiers, Session } from './types.js';\nimport { createKernlDownloads, type KernlDownloads } from './kernl-downloads.js';\nimport { createMultiplayerSettings } from './multiplayer/settings.js';\nimport { createStorageSecrets, type SecretsProvider } from './secrets/secrets.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 { createAppletTraffic } from './applets/traffic.js';\nimport { createGuardPipeline, type GuardPipeline } from './guard/pipeline.js';\nimport { createShellFirewall } from './kernl-firewall.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, resolveWindow } from './kernl-lifecycle.js';\nimport { createKernlIntents } from './kernl-intents.js';\nimport { loadCatalog, streamCatalog, type LoadCatalogOptions } 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 bridge: ShellBridge;\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 session on the active account and the outbox tier on where it publishes. */\nfunction followShellState({ bridge, accounts, session$, profiles, mailboxes, tiers }: ShellState): Subscription {\n const subscriptions = new Subscription();\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/**\n * The servers a running applet's manifest names, for the applet the bridges say asked. An applet's\n * own assets sit beside its artifact, and a `blossom:` reference usually names no server (D-055).\n */\nfunction manifestServersOf(handles: ReadonlyMap<string, MountedApplet>, requester: BridgeContext['requester']): readonly string[] {\n if (requester === 'shell') return [];\n for (const handle of handles.values()) {\n const { identity, manifest } = handle.summary;\n if (identity.dTag === requester.dTag && identity.hash === requester.hash) return manifest.servers;\n }\n return [];\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, handles: ReadonlyMap<string, MountedApplet>): 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({\n handoff: (uri) => host.openLink(uri),\n blossomServers: (requester) => manifestServersOf(handles, requester),\n ...(options.torrent ? { torrent: options.torrent } : {}),\n }),\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/**\n * The download programs and their services. An NZB an applet names by address is fetched through\n * the web bridge, so it meets the same address policy and size limit as any other fetch (D-050).\n */\nfunction downloadsFor(options: KernlOptions, bridges: Kernl['bridges'], identityOf: (windowId: string) => AppletIdentity | undefined, ownerOf: (windowId: string) => string | undefined): KernlDownloads & { readonly secrets: SecretsProvider } {\n const secrets = options.secrets ?? createStorageSecrets(options.host.storage);\n return { secrets, ...createKernlDownloads({\n host: options.host,\n options: options.downloads,\n secrets,\n identityOf,\n ownerOf,\n async fetchDocument(url, signal) {\n const result = await bridges.resolve(url, { requester: 'shell', signal });\n if (result.kind !== 'bytes') throw new Error('unavailable:not-a-document');\n return new Uint8Array(await result.response.arrayBuffer());\n },\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 downloads: { dispose(): void };\n readonly keys: { destroy(): void };\n readonly bridge: ShellBridge;\n readonly traffic: { close(): void };\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.downloads.dispose();\n parts.keys.destroy();\n parts.bridge.destroy();\n parts.traffic.close();\n parts.messaging?.close();\n parts.pool?.close();\n}\n\n/** The limit behind a quarantine, read from the profile in force as the applet crossed it. */\nfunction quarantineLimit(reason: string, config: GuardConfig): AppletStopLimit {\n const { limits, profile } = config;\n if (reason === 'flood:hidden-resource') return { cause: 'hidden-resource', count: limits.hiddenResourceAllowance, profile };\n return { cause: 'flood', count: limits.quarantineThreshold, windowMs: QUARANTINE_WINDOW_MS, profile };\n}\n\n/** The guard in front of kehto's bridge, which quarantines and releases through it. */\nfunction pipelineFor(options: KernlOptions, parts: { readonly handles: ReadonlyMap<string, MountedApplet>; readonly guardEvents$: Subject<GuardEvent>; readonly bridge: () => ShellBridge }): GuardPipeline {\n const { host } = options;\n const pipeline: GuardPipeline = createGuardPipeline({\n config: createGuardConfig(options.guard?.profile ?? 'strict'),\n ...(host.now ? { now: host.now.bind(host) } : {}),\n onEvent: (event) => parts.guardEvents$.next(event),\n onQuarantine: (windowId, _napplet, reason) => {\n parts.handles.get(windowId)?.revoked('quarantine', { limit: quarantineLimit(reason, pipeline.config) });\n parts.bridge().revokeNapplet(windowId, 'host');\n },\n getVisibility: (windowId) => host.getVisibility(windowId),\n onRelease: (windowId) => parts.bridge().releaseDeferred(windowId),\n });\n return pipeline;\n}\n\n/** The applet store's catalogue over the shell's pool, tiers and event cache. */\nfunction catalogFor(pool: RelayPool, tiers: RelayTiers, cached: Required<Pick<LoadCatalogOptions, 'cache' | 'store'>>): Kernl['catalog'] {\n return {\n load: (loadOptions) => loadCatalog(pool, tiers, { ...cached, ...loadOptions }),\n stream: (streamOptions) => streamCatalog(pool, tiers, { ...cached, ...streamOptions }),\n };\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 handles = new Map<string, MountedApplet>();\n const { messaging, bridges } = registriesFor(options, { eventStore, pool, tiers, accounts }, handles);\n\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 = pipelineFor(options, { handles, guardEvents$, bridge: () => bridge });\n const traffic = createAppletTraffic((windowId) => handles.has(windowId));\n\n const identityOf = (windowId: string): AppletIdentity | undefined => handles.get(windowId)?.summary.identity;\n const { eventCache, replaceableLoader, profiles, people, directory, mailboxes, files, signer } = createKernlNetwork(options, { eventStore, pool, tiers, accounts, destroyed$ });\n const lookupBefore = lookupReplaceable(eventStore, { loader: replaceableLoader, relays: () => [...tiers.get().outbox, ...tiers.get().discovery] });\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 downloads = downloadsFor(options, bridges, identityOf, (windowId) => handles.get(windowId)?.summary.manifest.catalogId);\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 people,\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, people, replaceableLoader, signer }, consent),\n uploader: uploaderFor(host, files, signer, identityOf),\n ...(isTheme(options.theme) ? { theme: options.theme } : {}),\n ...meeting.deps,\n shortcuts: { ...options.shortcuts, isFocused: (windowId) => pipeline.getVisibility(windowId).focused },\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 Object.assign(services.registry, { intent: intents.handler }, downloads.services);\n const guarding = createShellFirewall({ host, pipeline, handles, guardEvents$ });\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, detail }) => handles.get(windowId)?.revoked(reason, { detail }),\n onNappletMessage: (windowId, message) => traffic.fromApplet(windowId, 'port', message),\n filterNappletMessage: (windowId, message) => pipeline.observe(windowId, identityOf(windowId)?.dTag ?? 'unknown', message),\n getFocusContext: (windowId) => ({ focused: pipeline.getVisibility(windowId).focused }),\n permissions: guarding.permissions,\n ...(host.onShortcut ? { onShortcut: host.onShortcut.bind(host) } : {}),\n });\n const bridge = createShellBridge(adapter);\n grants = createGrants({ acl: bridge.runtime.aclState, storage: host.storage, availableDomains: () => [...buildShellCapabilities(adapter).domains, ...(downloads.extensions?.domains ?? [])] });\n bridge.registerConsentHandler(createConsentHandler(host, lookupBefore, identityOf));\n\n const { firewall, admissions } = guarding.attach(bridge.runtime);\n subscriptions.add(() => firewall.close());\n subscriptions.add(followShellState({ bridge, accounts, session$, profiles, mailboxes, tiers }));\n\n const lifecycle = createAppletLifecycle({\n pool,\n tiers,\n adapter,\n bridge,\n pipeline,\n admissions,\n remember: guarding.remember,\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 ?? [], ...(downloads.extensions ? { extensions: downloads.extensions } : {}),\n });\n\n return {\n accounts,\n eventStore,\n pool,\n bridge,\n guard: createGuardFacade(pipeline, guardEvents$),\n traffic$: traffic.traffic$,\n grants,\n relays: tiers,\n messaging,\n bridges,\n catalog: catalogFor(pool, tiers, { cache: eventCache.cacheRequest, store: eventStore }),\n profiles,\n people,\n mailboxes,\n files,\n multiplayer: meeting.multiplayer, downloads: downloads.programs, secrets: downloads.secrets.description,\n directory,\n intents: intents.intents,\n firewall,\n session$,\n get session() {\n return session$.value;\n },\n ...createSignIn(accounts),\n decodePointer,\n ...lifecycle,\n handleWindowMessage(event) {\n // Reported before kehto sees it: a message that gets the applet stopped is the one worth seeing.\n const from = resolveWindow(handles, event);\n if (from) traffic.fromApplet(from.windowId, 'window', event.data);\n lifecycle.handleWindowMessage(event);\n },\n destroy: () =>\n tearDown({ traffic, handles, subscriptions, destroyed$, network: { directory, eventCache }, intents, dm: services.dm, downloads, keys: services.keys, bridge, ...(ownsMessaging ? { messaging } : {}), ...(ownsPool ? { pool } : {}) }),\n };\n}\n","import { renderNappletNamespacePrelude, type NappletNamespacePreludeOptions } from '@kehto/shell';\n\n/**\n * One operation of a domain, as the applet calls it and as it travels: the request type,\n * the wire fields its arguments fill in order, and the field of the result it resolves with.\n *\n * The shape is `NappletBindingMethod` from kehto/web#413, declared here until a released\n * `@kehto/shell` exports it.\n */\nexport interface DomainBindingMethod {\n readonly type: string;\n readonly params: readonly string[];\n readonly reply: boolean;\n readonly result?: string;\n}\n\n/** What `window.napplet.<domain>` offers an applet: its operations and the messages the shell may push. */\nexport interface DomainBinding {\n readonly methods: Readonly<Record<string, DomainBindingMethod>>;\n readonly events?: readonly string[];\n readonly handlers?: Readonly<Record<string, readonly string[]>>;\n}\n\n/** Prelude options with the `bindings` kehto/web#413 adds; an older `@kehto/shell` ignores the field. */\nexport type BoundPreludeOptions = NappletNamespacePreludeOptions & { readonly bindings?: Readonly<Record<string, DomainBinding>> };\n\nconst call = (type: string, result: string, ...params: string[]): DomainBindingMethod => ({ type, params, reply: true, result });\n\nconst torrent = (action: string, result: string, ...params: string[]): DomainBindingMethod => call(`torrent.${action}`, result, ...params);\nconst nzb = (action: string, ...params: string[]): DomainBindingMethod => call(`nzb.${action}`, 'result', ...params);\nconst soulseek = (action: string, ...params: string[]): DomainBindingMethod => call(`soulseek.${action}`, 'value', ...params);\n\n/**\n * The applet-side bindings for the three download domains, one row per operation of\n * NAP-TORRENT, NAP-NZB and NAP-SOULSEEK's wire tables. The shell hands them to kehto's\n * namespace prelude, which turns each row into a method over the applet's private port.\n *\n * @example\n * ```ts\n * DOWNLOAD_BINDINGS.torrent?.methods.add; // { type: 'torrent.add', params: ['request'], reply: true, result: 'ack' }\n * Object.keys(DOWNLOAD_BINDINGS); // ['torrent', 'nzb', 'soulseek']\n * ```\n */\nexport const DOWNLOAD_BINDINGS: Readonly<Record<string, DomainBinding>> = Object.freeze({\n torrent: {\n methods: {\n capabilities: torrent('capabilities', 'capabilities'),\n pickFiles: torrent('pickFiles', 'result', 'options'),\n add: torrent('add', 'ack', 'request'),\n status: torrent('status', 'status', 'jobId'),\n jobs: torrent('jobs', 'jobs', 'filter'),\n files: torrent('files', 'files', 'jobId'),\n selectFiles: torrent('selectFiles', 'status', 'jobId', 'selection'),\n pause: torrent('pause', 'status', 'jobId'),\n resume: torrent('resume', 'status', 'jobId'),\n remove: torrent('remove', 'result', 'jobId', 'options'),\n metadata: torrent('metadata', 'result', 'jobId'),\n read: torrent('read', 'result', 'request'),\n exportMetainfo: torrent('exportMetainfo', 'result', 'jobId'),\n saveFile: torrent('saveFile', 'result', 'jobId', 'fileIndex'),\n openFile: torrent('openFile', 'result', 'jobId', 'fileIndex'),\n cancel: torrent('cancel', 'result', 'requestId'),\n update: torrent('update', 'result', 'request'),\n },\n events: ['torrent.state', 'torrent.progress', 'torrent.error'],\n handlers: { onState: ['torrent.state'], onProgress: ['torrent.progress'], onError: ['torrent.error'] },\n },\n nzb: {\n methods: {\n downloaders: nzb('downloaders'),\n add: nzb('add', 'request'),\n jobs: nzb('jobs', 'request'),\n status: nzb('status', 'jobId'),\n control: nzb('control', 'request'),\n files: nzb('files', 'request'),\n read: nzb('read', 'request'),\n },\n },\n soulseek: {\n methods: {\n info: soulseek('info'),\n search: soulseek('search', 'request'),\n browse: soulseek('browse', 'username'),\n results: soulseek('results', 'queryId', 'after', 'limit'),\n stop: soulseek('stop', 'queryId'),\n download: soulseek('download', 'fileId'),\n transfers: soulseek('transfers'),\n status: soulseek('status', 'transferId'),\n pause: soulseek('pause', 'transferId'),\n resume: soulseek('resume', 'transferId'),\n cancel: soulseek('cancel', 'transferId'),\n read: soulseek('read', 'transferId', 'offset', 'length'),\n save: soulseek('save', 'transferId'),\n release: soulseek('release', 'kind', 'handle'),\n },\n },\n});\n\nconst PROBE: BoundPreludeOptions = { domains: ['probe'], bindings: { probe: { methods: { ask: call('probe.ask', 'answer') } } } };\n\n/**\n * Whether the installed `@kehto/shell` can give an applet a domain it does not build in.\n *\n * An applet reaches the shell only through the port kehto's prelude keeps to itself, so a\n * domain kehto does not know is an empty object inside the applet unless the prelude is\n * given its binding table (kehto/web#413). kernl offers the download domains only when\n * this is true: a domain an applet can see but not call would be a promise the shell\n * cannot keep.\n *\n * @param render - The prelude renderer; kehto's by default.\n * @returns True when a binding passed to the prelude reaches its output.\n * @example\n * ```ts\n * supportsDomainBindings(); // false on @kehto/shell 0.35, true once it renders bindings\n * ```\n */\nexport function supportsDomainBindings(render: (options: NappletNamespacePreludeOptions) => string = renderNappletNamespacePrelude): boolean {\n return render(PROBE).includes('probe.ask');\n}\n","import { BehaviorSubject } from 'rxjs';\nimport {\n checkClientEndpoint,\n createNzbgetClient,\n createSabnzbdClient,\n createSlskdClient,\n createTransmissionClient,\n createUtorrentClient,\n detectClientEndpoint,\n type ClientEndpoint,\n type ClientFetch,\n type NzbClient,\n type PageScheme,\n type SoulseekClient,\n type TorrentClient,\n} from '@kernlize/bridges';\nimport { createNamespacedStore } from '../persistence/store.js';\nimport { createStorageSecrets, type SecretsProvider } from '../secrets/secrets.js';\nimport type { StorageLike } from '../types.js';\nimport type { ClientFor, ConnectionRouting, DownloadClients, DownloadClientsState, DownloadConnection, DownloadDomain, DownloadProgram, DownloadSignIn, RoutedClient } from './connections.js';\nimport { defaultLabel, domainOf, isSignInText, labelFrom, nextRoutingKey, readStoredState, successor, withDefaults } from './download-records.js';\n\nexport type { CheckedConnection, ClientFor, ConnectionChange, ConnectionRouting, DownloadClients, DownloadClientsState, DownloadConnection, DownloadDomain, DownloadProgram, DownloadSignIn, RoutedClient, RoutedDomain } from './connections.js';\nexport { DOWNLOAD_PROGRAMS, type DownloadProgramInfo } from './download-records.js';\n\nconst STORAGE_KEY = 'download-programs:v1';\nconst SECRET_FIELDS = ['password', 'apiKey'] as const;\n\n/** Options for {@link createDownloadClients}. */\nexport interface DownloadClientsOptions {\n readonly storage: StorageLike;\n /** Where passwords and keys are kept; the host's storage, as typed, by default. */\n readonly secrets?: SecretsProvider;\n /** How the page running kernl was loaded; read from `location` by default, `http` where there is none. */\n readonly pageScheme?: () => PageScheme;\n /** `fetch` for every program; the global one by default. */\n readonly fetch?: ClientFetch;\n}\n\ntype AnyClient = TorrentClient | NzbClient | SoulseekClient;\ntype SecretField = (typeof SECRET_FIELDS)[number];\ntype Secrets = Readonly<Partial<Record<SecretField, string>>>;\n\n/** A built client and what it was built from, so it is rebuilt only when one of those changes. */\ninterface Built {\n readonly url: string;\n readonly username: string | undefined;\n readonly secrets: Secrets;\n readonly client: AnyClient;\n}\n\nconst FACTORIES: Readonly<Record<DownloadProgram, (options: { endpoint: ClientEndpoint; fetch?: ClientFetch }) => AnyClient>> = {\n transmission: createTransmissionClient,\n utorrent: createUtorrentClient,\n nzbget: createNzbgetClient,\n sabnzbd: createSabnzbdClient,\n slskd: createSlskdClient,\n};\n\n/**\n * How the page running the shell was loaded, from `location`. Where there is no page, as in a\n * host outside a browser, nothing restricts which addresses can be called, which is `http`'s rule.\n *\n * @returns `https` for a page loaded over it, otherwise `http`.\n * @example\n * ```ts\n * currentPageScheme(); // 'https' on https://kernl.run/app/\n * ```\n */\nexport function currentPageScheme(): PageScheme {\n return (globalThis as { location?: { protocol?: string } }).location?.protocol === 'https:' ? 'https' : 'http';\n}\n\n/** The name a connection's secret is kept under with the provider. */\nconst secretName = (id: string, field: SecretField): string => `download:${id}:${field}`;\n\nconst secretsOf = (signIn: DownloadSignIn): Secrets => ({ ...(signIn.password ? { password: signIn.password } : {}), ...(signIn.apiKey ? { apiKey: signIn.apiKey } : {}) });\n\n/** The sign-in with its address replaced and empty fields dropped, or a thrown `invalid:sign-in` when a field is not text of a sane length. */\nfunction tidy(signIn: DownloadSignIn, url: string): DownloadSignIn {\n const { username, password, apiKey } = signIn;\n if (!isSignInText(username) || !isSignInText(password) || !isSignInText(apiKey)) throw new Error('invalid:sign-in');\n return { url, ...(username ? { username } : {}), ...secretsOf(signIn) };\n}\n\n/** The address as this page may call it, or the thrown reason it may not. */\nfunction callable(url: string, page: PageScheme): string {\n const checked = checkClientEndpoint(url, page);\n if (!checked.ok) throw new Error(checked.reason);\n return checked.url;\n}\n\n/** What is typed, with a secret left empty filled from what is kept for exactly this address of this connection. */\nfunction withKeptSecrets(kept: Secrets | undefined, typed: DownloadSignIn, url: string): DownloadSignIn {\n const password = typed.password || kept?.password;\n const apiKey = typed.apiKey || kept?.apiKey;\n return tidy({ url, ...(typed.username === undefined ? {} : { username: typed.username }), ...(password ? { password } : {}), ...(apiKey ? { apiKey } : {}) }, url);\n}\n\n/** One domain's routing, reading the settings on every call so an edit or removal is seen at once. */\nfunction routingOver<D extends DownloadDomain>(state: () => DownloadClientsState, clientOf: (connection: DownloadConnection) => AnyClient | undefined, domain: D): ConnectionRouting<ClientFor<D>> {\n const all = (): RoutedClient<ClientFor<D>>[] =>\n state().connections.flatMap((connection) => {\n const client = domainOf(connection.program) === domain ? clientOf(connection) : undefined;\n return client ? [{ connection, client: client as ClientFor<D> }] : [];\n });\n return {\n all,\n byId: (id) => all().find((routed) => routed.connection.id === id),\n preferred() {\n const serving = all();\n const chosen = (state().defaults as Readonly<Record<string, string | undefined>>)[domain];\n return serving.find((routed) => routed.connection.id === chosen) ?? serving[0];\n },\n };\n}\n\n/** What settings keep for a connection signed in to as `signIn`. */\nfunction described(base: Pick<DownloadConnection, 'id' | 'program' | 'label' | 'routingKey'>, signIn: DownloadSignIn): DownloadConnection {\n const { id, program, label, routingKey } = base;\n return { id, program, label, url: signIn.url, ...(signIn.username ? { username: signIn.username } : {}), hasPassword: signIn.password !== undefined, hasApiKey: signIn.apiKey !== undefined, routingKey };\n}\n\n/**\n * The person's download connections, and the routing the `torrent`, `nzb` and `soulseek`\n * services read (D-050, D-053). A person may set up any number of connections, several of the\n * same program among them; each has a random id and a label of their own.\n *\n * Addresses, usernames and labels are kept on this device at `kernl:download-programs:v1`.\n * Passwords and keys are not: they go to the secrets provider under\n * `download:<connection id>:password` and `…:apiKey`, and are held in memory only for the\n * clients that sign in with them, so nothing that reads settings, the settings form included,\n * is ever handed one (D-052). A connection serves nobody until the provider has answered for\n * its kept sign-in, and none whose sign-in the provider will not hand over (it is `locked`).\n *\n * An address is checked against how kernl itself is served before it is kept or used: a page\n * loaded over `https` may call a plain `http` address only on this device, so anything else is\n * refused as `invalid:mixed-content`. An address typed without a scheme has it worked out by\n * asking the program, `https` first. What comes back out of storage is checked again and\n * dropped when it no longer passes.\n *\n * @param options - Storage, and optionally the secrets provider, how the page was loaded and the `fetch` to use.\n * @returns The settings and the routing built from them.\n * @example\n * ```ts\n * const programs = createDownloadClients({ storage: localStorage });\n * const { signIn } = await programs.check('transmission', { url: 'localhost:9091', username: 'me', password: 'secret' });\n * const home = await programs.add('transmission', signIn, 'Home');\n * await programs.routing('torrent').byId(home.id)?.client.list();\n * ```\n */\nexport function createDownloadClients(options: DownloadClientsOptions): DownloadClients {\n const store = createNamespacedStore(options.storage, 'kernl');\n const secrets = options.secrets ?? createStorageSecrets(options.storage);\n const page = options.pageScheme ?? currentPageScheme;\n const state$ = new BehaviorSubject<DownloadClientsState>(readStoredState(store.getJson<unknown>(STORAGE_KEY, {}), page()));\n const held = new Map<string, Secrets>();\n const built = new Map<string, Built>();\n\n const build = (program: DownloadProgram, endpoint: ClientEndpoint): AnyClient => FACTORIES[program]({ endpoint, ...(options.fetch ? { fetch: options.fetch } : {}) });\n\n /** One client per connection, so its signed-in session lasts until the address, username or secrets change; a label does not count. */\n function clientOf(connection: DownloadConnection): AnyClient | undefined {\n const kept = held.get(connection.id);\n if (!kept) return undefined;\n const cached = built.get(connection.id);\n if (cached?.url === connection.url && cached.username === connection.username && cached.secrets === kept) return cached.client;\n const client = build(connection.program, { url: connection.url, ...(connection.username ? { username: connection.username } : {}), ...kept });\n built.set(connection.id, { url: connection.url, username: connection.username, secrets: kept, client });\n return client;\n }\n\n function commit(connections: readonly DownloadConnection[], wanted: Readonly<Record<string, unknown>> = state$.value.defaults, locked: readonly string[] = state$.value.locked): void {\n const next = withDefaults(connections, wanted, locked);\n store.setJson(STORAGE_KEY, { connections: next.connections, defaults: next.defaults });\n state$.next(next);\n }\n\n const find = (id: string): DownloadConnection | undefined => state$.value.connections.find((connection) => connection.id === id);\n function known(id: string, program?: DownloadProgram): DownloadConnection {\n const connection = find(id);\n if (!connection || (program !== undefined && connection.program !== program)) throw new Error('invalid:connection');\n return connection;\n }\n\n const withKept = (existing: DownloadConnection | undefined, typed: DownloadSignIn, url: string): DownloadSignIn => withKeptSecrets(existing?.url === url ? held.get(existing.id) : undefined, typed, url);\n\n /** The provider keeps the secrets before settings say they are kept, so a refusal leaves what was there. */\n async function keep(id: string, signIn: DownloadSignIn): Promise<void> {\n await Promise.all(SECRET_FIELDS.map((field) => (signIn[field] ? secrets.set(secretName(id, field), signIn[field]) : secrets.delete(secretName(id, field)))));\n held.set(id, secretsOf(signIn));\n }\n\n async function load(connection: DownloadConnection): Promise<void> {\n const ask = (field: SecretField, kept: boolean): Promise<string | undefined> | undefined => (kept ? secrets.get(secretName(connection.id, field)) : undefined);\n try {\n const [password, apiKey] = await Promise.all([ask('password', connection.hasPassword), ask('apiKey', connection.hasApiKey)]);\n // A secret settings say is kept and the provider no longer has is gone, not empty: signing in without it would only be refused.\n if ((connection.hasPassword && !password) || (connection.hasApiKey && !apiKey)) throw new Error('unavailable:secrets');\n held.set(connection.id, { ...(password ? { password } : {}), ...(apiKey ? { apiKey } : {}) });\n } catch {\n state$.next({ ...state$.value, locked: [...state$.value.locked, connection.id] });\n }\n }\n\n const ready = Promise.all(state$.value.connections.map(load)).then(() => undefined);\n\n return {\n state$: state$.asObservable(),\n state: () => state$.value,\n ready,\n async check(program, typed, existing) {\n await ready;\n const kept = existing === undefined ? undefined : known(existing, program);\n let signIn = typed;\n const { endpoint, result } = await detectClientEndpoint(typed.url, page(), (url) => {\n signIn = withKept(kept, typed, url);\n return build(program, signIn).probe();\n });\n return { signIn: { ...signIn, url: endpoint.url }, notes: endpoint.notes, probe: result };\n },\n async add(program, typed, label) {\n await ready;\n const url = callable(typed.url, page());\n const name = label === undefined ? defaultLabel(program, state$.value.connections) : labelFrom(label);\n const signIn = withKept(undefined, typed, url);\n const id = crypto.randomUUID();\n await keep(id, signIn);\n const connection = described({ id, program, label: name, routingKey: `${id}:0` }, signIn);\n commit([...state$.value.connections, connection]);\n return connection;\n },\n async update(id, change) {\n await ready;\n const current = known(id);\n const label = change.label === undefined ? current.label : labelFrom(change.label);\n let next: DownloadConnection = { ...current, label };\n let locked = state$.value.locked;\n if (change.signIn) {\n const signIn = withKept(current, change.signIn, callable(change.signIn.url, page()));\n await keep(id, signIn);\n next = described({ ...next, routingKey: signIn.url === current.url ? current.routingKey : nextRoutingKey(current) }, signIn);\n locked = locked.filter((entry) => entry !== id);\n }\n commit(state$.value.connections.map((connection) => (connection.id === id ? next : connection)), state$.value.defaults, locked);\n return next;\n },\n async remove(id) {\n await ready;\n const current = find(id);\n if (!current) return;\n await Promise.all(SECRET_FIELDS.map((field) => secrets.delete(secretName(id, field))));\n held.delete(id);\n built.delete(id);\n const { connections, defaults, locked } = state$.value;\n const wanted: Record<string, unknown> = { ...defaults };\n const domain = domainOf(current.program);\n if (wanted[domain] === id) wanted[domain] = successor(connections, current)?.id;\n commit(connections.filter((connection) => connection.id !== id), wanted, locked.filter((entry) => entry !== id));\n },\n chooseDefault(domain, id) {\n const connection = find(id);\n if (!connection || domainOf(connection.program) !== domain) throw new Error('invalid:connection');\n commit(state$.value.connections, { ...state$.value.defaults, [domain]: id });\n },\n routing: (domain) => routingOver(() => state$.value, clientOf, domain),\n };\n}\n","import type { StorageLike } from '../types.js';\n\n/** How a secrets provider keeps what it is given, so the shell can say so truthfully. */\nexport interface SecretsDescription {\n /** What the provider is, in a few plain words: \"this browser\", \"the system keychain\". */\n readonly label: string;\n /**\n * `plain`: kept as typed, readable by anything that can read the shell's storage.\n * `protected`: kept by something that guards it, such as a keychain, an extension or a service that asks before it answers.\n * `session`: kept in memory only, gone when the shell closes.\n */\n readonly keeps: 'plain' | 'protected' | 'session';\n}\n\n/**\n * Where the shell keeps what must not be shown again: the passwords and keys of the\n * services it signs in to for the person. It is one small contract so a host can put\n * its own keeper behind it: a browser extension, a service running on the device, the\n * platform's keychain in a native shell.\n *\n * Names are the shell's own, such as `download:transmission:password`; a provider keeps\n * them apart from anything else it holds and never interprets them. Every method may\n * reject with `unavailable:secrets` (the keeper cannot be reached) or `denied:secrets`\n * (it, or the person, said no); a caller treats both as \"not available now\", never as\n * \"there is no secret\". Identity keys are not kept here: they live in signers (SOUL opinion 1).\n */\nexport interface SecretsProvider {\n readonly description: SecretsDescription;\n /** The secret under a name, or undefined when there is none. */\n get(name: string): Promise<string | undefined>;\n /** Keep a secret under a name, replacing any that was there. */\n set(name: string, value: string): Promise<void>;\n /** Forget the secret under a name; forgetting one that is not there succeeds. */\n delete(name: string): Promise<void>;\n}\n\nconst STORAGE_PREFIX = 'kernl:secrets:v1:';\n\n/**\n * The default provider: secrets kept in the host's storage, as typed. It protects nothing\n * beyond what the storage itself does, and says so (`keeps: 'plain'`); a host that can do\n * better passes its own provider as `KernlOptions.secrets`.\n *\n * @param storage - The host's storage; each secret is one key under `kernl:secrets:v1:`.\n * @returns A provider over that storage; `set` rejects `unavailable:secrets` when the storage refuses the write.\n * @example\n * ```ts\n * const secrets = createStorageSecrets(localStorage);\n * await secrets.set('download:sabnzbd:apiKey', 'k1');\n * await secrets.get('download:sabnzbd:apiKey'); // 'k1'\n * ```\n */\nexport function createStorageSecrets(storage: StorageLike): SecretsProvider {\n return {\n description: { label: 'this device', keeps: 'plain' },\n get: async (name) => storage.getItem(STORAGE_PREFIX + name) ?? undefined,\n async set(name, value) {\n try {\n storage.setItem(STORAGE_PREFIX + name, value);\n } catch {\n // Storage that is full or switched off refuses the write; the reason says only that, never the value.\n throw new Error('unavailable:secrets');\n }\n },\n delete: async (name) => storage.removeItem(STORAGE_PREFIX + name),\n };\n}\n\n/**\n * A provider that keeps secrets in memory only, for a host that wants nothing written\n * down and for a shell that is tried without leaving a trace.\n *\n * @returns A provider whose secrets end with it.\n * @example\n * ```ts\n * const kernl = createKernl({ host, secrets: createMemorySecrets() });\n * ```\n */\nexport function createMemorySecrets(): SecretsProvider {\n const held = new Map<string, string>();\n return {\n description: { label: 'this session', keeps: 'session' },\n get: async (name) => held.get(name),\n set: async (name, value) => void held.set(name, value),\n delete: async (name) => void held.delete(name),\n };\n}\n","import { checkClientEndpoint, type PageScheme } from '@kernlize/bridges';\nimport type { DownloadClientsState, DownloadConnection, DownloadDomain, DownloadProgram, RoutedDomain } from './connections.js';\n\n/** What a program is for, and what it asks for before it answers. */\nexport interface DownloadProgramInfo {\n /** The NAP domain the program serves. */\n readonly domain: DownloadDomain;\n /** The program's own name, as its makers write it. */\n readonly name: string;\n /** Which sign-in fields the program takes. */\n readonly signIn: readonly ('username' | 'password' | 'apiKey')[];\n /** An address the program answers at when it runs on this device with its usual settings. */\n readonly example: string;\n}\n\n/**\n * Every program kernl can drive, with the domain it serves and the sign-in it takes.\n *\n * @example\n * ```ts\n * DOWNLOAD_PROGRAMS.sabnzbd.signIn; // ['apiKey']\n * DOWNLOAD_PROGRAMS.transmission.domain; // 'torrent'\n * ```\n */\nexport const DOWNLOAD_PROGRAMS: Readonly<Record<DownloadProgram, DownloadProgramInfo>> = Object.freeze({\n transmission: { domain: 'torrent', name: 'Transmission', signIn: ['username', 'password'], example: 'http://localhost:9091' },\n utorrent: { domain: 'torrent', name: 'uTorrent', signIn: ['username', 'password'], example: 'http://localhost:8080' },\n nzbget: { domain: 'nzb', name: 'NZBGet', signIn: ['username', 'password'], example: 'http://localhost:6789' },\n sabnzbd: { domain: 'nzb', name: 'SABnzbd', signIn: ['apiKey'], example: 'http://localhost:8080' },\n slskd: { domain: 'soulseek', name: 'slskd', signIn: ['apiKey', 'username', 'password'], example: 'http://localhost:5030' },\n});\n\nconst MAX_TEXT_LENGTH = 512;\nconst MAX_LABEL_LENGTH = 60;\nconst ROUTED: readonly RoutedDomain[] = ['torrent', 'soulseek'];\nconst ID = /^[A-Za-z0-9-]{1,64}$/;\nconst GENERATION = /^\\d{1,9}$/;\n\ntype Defaults = Partial<Record<RoutedDomain, string>>;\n\n/** Whether a sign-in field is absent or text of a sane length. */\nexport const isSignInText = (value: unknown): value is string | undefined => value === undefined || (typeof value === 'string' && value.length <= MAX_TEXT_LENGTH);\n\n/** The domain a program serves. */\nexport const domainOf = (program: DownloadProgram): DownloadDomain => DOWNLOAD_PROGRAMS[program].domain;\n\n/** A label the person typed, trimmed; a thrown `invalid:label` unless it is 1 to 60 characters. */\nexport function labelFrom(value: string): string {\n const label = value.trim();\n if (label.length < 1 || label.length > MAX_LABEL_LENGTH) throw new Error('invalid:label');\n return label;\n}\n\n/** The program's name, numbered from 2 while another connection already goes by it. */\nexport function defaultLabel(program: DownloadProgram, connections: readonly DownloadConnection[]): string {\n const name = DOWNLOAD_PROGRAMS[program].name;\n const taken = new Set(connections.map((connection) => connection.label));\n let label = name;\n for (let n = 2; taken.has(label); n += 1) label = `${name} ${n}`;\n return label;\n}\n\n/** The routing key for a connection whose address just changed: the same id, the next generation. */\nexport function nextRoutingKey(connection: DownloadConnection): string {\n return `${connection.id}:${Number(connection.routingKey.slice(connection.id.length + 1)) + 1}`;\n}\n\n/**\n * The state with every routed domain's default naming one of its connections: the one wanted\n * when it is there, else the first of the domain in added order; none when the domain has none.\n */\nexport function withDefaults(connections: readonly DownloadConnection[], wanted: Readonly<Record<string, unknown>>, locked: readonly string[]): DownloadClientsState {\n const defaults: Defaults = {};\n for (const domain of ROUTED) {\n const serving = connections.filter((connection) => domainOf(connection.program) === domain);\n const chosen = serving.find((connection) => connection.id === wanted[domain]) ?? serving[0];\n if (chosen) defaults[domain] = chosen.id;\n }\n return { connections, defaults, locked };\n}\n\n/** The connection of the same domain added after the one removed, else the first other one; the next default. */\nexport function successor(connections: readonly DownloadConnection[], removed: DownloadConnection): DownloadConnection | undefined {\n const domain = domainOf(removed.program);\n const serving = connections.filter((connection) => domainOf(connection.program) === domain);\n return serving[serving.indexOf(removed) + 1] ?? serving.find((connection) => connection !== removed);\n}\n\nconst isProgram = (value: unknown): value is DownloadProgram => typeof value === 'string' && Object.hasOwn(DOWNLOAD_PROGRAMS, value);\n\nfunction isLabel(value: unknown): value is string {\n return typeof value === 'string' && value === value.trim() && value.length >= 1 && value.length <= MAX_LABEL_LENGTH;\n}\n\n/** What was stored, when it is still a connection this page may use; undefined otherwise, so nothing stored is trusted as it stands. */\nfunction usable(value: unknown, page: PageScheme): DownloadConnection | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const { id, program, label, url, username, routingKey, hasPassword, hasApiKey } = value as Record<string, unknown>;\n if (typeof id !== 'string' || !ID.test(id) || !isProgram(program) || !isLabel(label) || !isSignInText(username)) return undefined;\n if (typeof routingKey !== 'string' || !routingKey.startsWith(`${id}:`) || !GENERATION.test(routingKey.slice(id.length + 1))) return undefined;\n const checked = typeof url === 'string' ? checkClientEndpoint(url, page) : undefined;\n if (!checked?.ok) return undefined;\n return { id, program, label, url: checked.url, ...(username ? { username } : {}), hasPassword: hasPassword === true, hasApiKey: hasApiKey === true, routingKey };\n}\n\n/**\n * The settings as stored, read as untrusted: a damaged entry, an unknown program, an address\n * this page may not call or a second entry under an id already read is dropped, and a default\n * that names no connection of its domain is replaced by the first that is.\n */\nexport function readStoredState(value: unknown, page: PageScheme): DownloadClientsState {\n const stored = (typeof value === 'object' && value !== null ? value : {}) as { connections?: unknown; defaults?: unknown };\n const connections: DownloadConnection[] = [];\n for (const entry of Array.isArray(stored.connections) ? stored.connections : []) {\n const connection = usable(entry, page);\n if (connection && !connections.some((kept) => kept.id === connection.id)) connections.push(connection);\n }\n const wanted = typeof stored.defaults === 'object' && stored.defaults !== null ? (stored.defaults as Record<string, unknown>) : {};\n return withDefaults(connections, wanted, []);\n}\n","import type { NamespacedStore } from '../persistence/store.js';\n\nconst STORE_KEY = 'nzb-handles:v1';\n\n/** The job a handle stands for; `gone` once the downloader no longer has it, after which the handle is never bound again. */\nexport interface NzbJobHandle {\n readonly applet: string;\n /** The handle the applet holds. */\n readonly id: string;\n /** The downloader's key in the shell. */\n readonly key: string;\n /** The downloader's own id for the job. */\n readonly backend: string;\n readonly gone: boolean;\n}\n\ninterface DownloaderHandle {\n readonly applet: string;\n readonly id: string;\n readonly key: string;\n}\n\ninterface CategoryHandle extends DownloaderHandle {\n /** The downloader's own name for the category. */\n readonly name: string;\n}\n\ninterface HandleTable {\n downloaders: DownloaderHandle[];\n categories: CategoryHandle[];\n jobs: NzbJobHandle[];\n}\n\n/** The shell-issued names an applet knows downloaders, categories and jobs by, kept so they survive a reload. */\nexport interface NzbHandles {\n /** The applet's handle for a downloader, issued on first use. */\n downloaderId(applet: string, key: string): string;\n /** The downloader key a handle of this applet stands for. */\n downloaderKey(applet: string, id: string): string | undefined;\n /** The applet's handle for a downloader's category; issued on first use when `issue` is set. */\n categoryId(applet: string, key: string, name: string, issue?: boolean): string | undefined;\n /** The downloader's own category name a handle of this applet stands for on that downloader. */\n categoryName(applet: string, key: string, id: string): string | undefined;\n /** The applet's handle for a job it submitted; a new one unless a live handle already stands for that job. */\n jobId(applet: string, key: string, backend: string): string;\n /** The job a handle of this applet stands for, gone or not. */\n job(applet: string, id: string): NzbJobHandle | undefined;\n /** The applet's jobs on one downloader that are not gone. */\n jobs(applet: string, key: string): readonly NzbJobHandle[];\n /** Marks a job gone: the handle answers `not_found` from now on and is never bound to another job. */\n retire(applet: string, id: string): void;\n /** Drops the applet's gone handles that nothing can replay any more. */\n forget(applet: string, keep: ReadonlySet<string>): void;\n}\n\ntype Row = Readonly<Record<string, unknown>>;\n\nfunction rows<T>(value: unknown, fields: Readonly<Record<string, string>>): T[] {\n if (!Array.isArray(value)) return [];\n const sound = (row: unknown): boolean => typeof row === 'object' && row !== null && Object.entries(fields).every(([field, type]) => typeof (row as Row)[field] === type);\n return value.filter(sound) as T[];\n}\n\nconst TEXT = { applet: 'string', id: 'string', key: 'string' } as const;\n\n/**\n * The handle table over the shell's store. Handles are random, mean nothing outside\n * the applet they were issued to, and never carry a downloader's key, a category's own\n * name or a job's own id (NAP-NZB, Common values). Whatever comes back out of storage\n * is checked row by row; a row that is not sound is set aside.\n *\n * @param store - The shell's namespaced store.\n * @returns The handle table.\n * @example\n * ```ts\n * const handles = createNzbHandles(createNamespacedStore(localStorage, 'kernl'));\n * handles.downloaderId('reader', 'nzbget'); // '3f0c…'\n * ```\n */\nexport function createNzbHandles(store: NamespacedStore): NzbHandles {\n const load = (): HandleTable => {\n const raw = store.getJson<Row | null>(STORE_KEY, null) ?? {};\n return {\n downloaders: rows(raw.downloaders, TEXT),\n categories: rows(raw.categories, { ...TEXT, name: 'string' }),\n jobs: rows(raw.jobs, { ...TEXT, backend: 'string', gone: 'boolean' }),\n };\n };\n const issue = <T extends DownloaderHandle>(pick: (table: HandleTable) => T[], row: Omit<T, 'id'>): string => {\n const table = load();\n const id = crypto.randomUUID();\n pick(table).push({ ...row, id } as T);\n store.setJson(STORE_KEY, table);\n return id;\n };\n const mine = <T extends DownloaderHandle>(list: readonly T[], applet: string, key: string): T[] => list.filter((row) => row.applet === applet && row.key === key);\n return {\n downloaderId: (applet, key) => mine(load().downloaders, applet, key)[0]?.id ?? issue((table) => table.downloaders, { applet, key }),\n downloaderKey: (applet, id) => load().downloaders.find((row) => row.applet === applet && row.id === id)?.key,\n categoryId(applet, key, name, create = false) {\n const known = mine(load().categories, applet, key).find((row) => row.name === name)?.id;\n return known ?? (create ? issue((table) => table.categories, { applet, key, name }) : undefined);\n },\n categoryName: (applet, key, id) => mine(load().categories, applet, key).find((row) => row.id === id)?.name,\n jobId(applet, key, backend) {\n const live = mine(load().jobs, applet, key).find((row) => row.backend === backend && !row.gone)?.id;\n return live ?? issue((table) => table.jobs, { applet, key, backend, gone: false });\n },\n job: (applet, id) => load().jobs.find((row) => row.applet === applet && row.id === id),\n jobs: (applet, key) => mine(load().jobs, applet, key).filter((row) => !row.gone),\n retire(applet, id) {\n const table = load();\n table.jobs = table.jobs.map((row) => (row.applet === applet && row.id === id ? { ...row, gone: true } : row));\n store.setJson(STORE_KEY, table);\n },\n forget(applet, keep) {\n const table = load();\n table.jobs = table.jobs.filter((row) => row.applet !== applet || !row.gone || keep.has(row.id));\n store.setJson(STORE_KEY, table);\n },\n };\n}\n","/**\n * NAP-NZB wire shapes, written out here from the draft's tables.\n *\n * Upstream gap: `@napplet/core` 0.41 publishes no NAP-NZB types; the draft is\n * napplet/naps PR #136. Replace this file with the upstream types when they ship.\n */\n\n/** Every error code NAP-NZB names. */\nexport type NzbErrorCode =\n | 'invalid_request'\n | 'permission_denied'\n | 'not_found'\n | 'unsupported'\n | 'invalid_state'\n | 'invalid_range'\n | 'not_ready'\n | 'file_changed'\n | 'limit_exceeded'\n | 'rate_limited'\n | 'authentication_required'\n | 'unavailable'\n | 'backend_rejected'\n | 'mutation_failed'\n | 'backend_error'\n | 'conflict'\n | 'outcome_unknown';\n\n/** `NZBError`: why a request failed, in words an applet may show. */\nexport interface NzbError {\n readonly code: NzbErrorCode;\n readonly message: string;\n /** Present exactly when a mutation record exists. */\n readonly replayUntil?: number;\n}\n\n/** `JobState`: a job's normalised phase. */\nexport type NzbJobState = 'queued' | 'downloading' | 'paused' | 'processing' | 'completed' | 'failed' | 'cancelled' | 'skipped' | 'unknown';\n\n/** `JobAction`: what can be asked of one job. */\nexport type NzbJobAction = 'pause' | 'resume' | 'cancel' | 'retry' | 'forget' | 'delete';\n\n/** An optional submission field a downloader can honour. */\nexport type NzbAddOption = 'categoryId' | 'priority' | 'startPaused' | 'password';\n\n/** `Category`: one category choice a downloader offers. */\nexport interface NzbCategoryInfo {\n readonly categoryId: string;\n readonly label: string;\n readonly description: string;\n}\n\n/** `Downloader`: one downloader as discovery describes it. */\nexport interface NzbDownloaderInfo {\n readonly downloaderId: string;\n readonly label: string;\n readonly canAdd: boolean;\n readonly sourceKinds: readonly ('bytes' | 'url')[];\n readonly addOptions: readonly NzbAddOption[];\n readonly categories: readonly NzbCategoryInfo[];\n readonly actions: readonly NzbJobAction[];\n readonly canReadFiles: boolean;\n readonly maxNZBBytes: number;\n readonly maxPageSize: number;\n readonly maxReadBytes: number;\n readonly replaySeconds: number;\n}\n\n/** `DownloadersResult`. */\nexport interface NzbDownloadersResult {\n readonly downloaders: readonly NzbDownloaderInfo[];\n}\n\n/** `NZBSource`: exactly one NZB document, as bytes or by address. */\nexport type NzbSource = { readonly kind: 'bytes'; readonly dataBase64: string } | { readonly kind: 'url'; readonly url: string };\n\n/** `AddRequest`. */\nexport interface NzbAddRequest {\n readonly downloaderId: string;\n readonly operationKey: string;\n readonly source: NzbSource;\n readonly name?: string;\n readonly categoryId?: string;\n readonly priority?: 'low' | 'normal' | 'high';\n readonly startPaused?: boolean;\n readonly password?: string;\n}\n\n/** `Job`: one observation of one job. */\nexport interface NzbJob {\n readonly jobId: string;\n readonly downloaderId: string;\n readonly name: string;\n readonly state: NzbJobState;\n readonly observedAt: number;\n readonly actions: readonly NzbJobAction[];\n readonly canReadFiles: boolean;\n readonly categoryId?: string;\n readonly downloadPaused?: boolean;\n readonly downloadProgress?: number;\n readonly downloadedBytes?: number;\n readonly totalBytes?: number;\n readonly downloadRate?: number;\n readonly stage?: string;\n readonly message?: string;\n}\n\n/** `AddResult`. */\nexport interface NzbAddResult {\n readonly job: NzbJob;\n readonly replayUntil: number;\n}\n\n/** `JobsRequest`, and `FilesRequest` with `jobId` in place of `downloaderId`. */\nexport interface NzbJobsRequest {\n readonly downloaderId: string;\n readonly after?: string;\n readonly limit?: number;\n}\n\n/** `JobsResult`. */\nexport interface NzbJobsResult {\n readonly jobs: readonly NzbJob[];\n readonly next: string | null;\n}\n\n/** `ControlRequest`. */\nexport interface NzbControlRequest {\n readonly jobId: string;\n readonly operationKey: string;\n readonly action: NzbJobAction;\n}\n\n/** `ControlResult`. */\nexport interface NzbControlResult {\n readonly jobId: string;\n readonly action: NzbJobAction;\n /** Present for pause, resume, cancel and retry. */\n readonly job?: NzbJob;\n readonly replayUntil: number;\n}\n\n/**\n * The limits this shell advertises for every downloader. kernl is a remote\n * control, so nothing can be read back: `maxReadBytes` is zero.\n *\n * @example\n * ```ts\n * NZB_LIMITS.maxNZBBytes; // 10485760\n * ```\n */\nexport const NZB_LIMITS = { maxNZBBytes: 10 * 1024 * 1024, maxPageSize: 100, maxReadBytes: 0, replaySeconds: 86_400 } as const;\n\n/**\n * Every job action, in the order the draft lists them.\n *\n * @example\n * ```ts\n * NZB_ACTIONS.includes('pause'); // true\n * ```\n */\nexport const NZB_ACTIONS: readonly NzbJobAction[] = ['pause', 'resume', 'cancel', 'retry', 'forget', 'delete'];\n\n/** A failure on its way to an applet: a code, plain words, and the replay boundary when a record exists. */\nexport class NzbFault extends Error {\n constructor(\n readonly code: NzbErrorCode,\n message: string,\n readonly replayUntil?: number,\n ) {\n super(message);\n }\n}\n\n/**\n * Stops the request with a NAP-NZB error unless a condition holds.\n *\n * @param condition - What must be true to carry on.\n * @param code - The NAP-NZB error code otherwise.\n * @param message - Plain words for the applet: no address, path, credential or backend id.\n * @returns Nothing; narrows `condition` to truthy.\n * @example\n * ```ts\n * need(typeof id === 'string', 'invalid_request', 'The request was not understood');\n * ```\n */\nexport function need(condition: unknown, code: NzbErrorCode, message: string): asserts condition {\n if (!condition) throw new NzbFault(code, message);\n}\n","import { NZB_LIMITS } from './nzb-wire.js';\n\n/** What the shell reads from an NZB document before handing it on. */\nexport interface NzbDocument {\n /** How many files the document lists. */\n readonly files: number;\n /** The document's own title, tidied for display, or a plain stand-in. */\n readonly name: string;\n}\n\nconst NAMESPACE = 'http://www.newzbin.com/DTD/2003/nzb';\nconst MAX_DEPTH = 16;\nconst MAX_ELEMENTS = 20_000;\nconst MAX_NAME_LENGTH = 120;\nconst UNNAMED = 'NZB download';\n\nconst NAME = '[\\\\p{L}_][\\\\p{L}\\\\p{N}_.-]*';\nconst QNAME = `${NAME}(?::${NAME})?`;\nconst QUOTED = `(?:\"[^\"]*\"|'[^']*')`;\nconst DECLARATION = /^<\\?xml\\s[^?]*\\?>/;\nconst ENCODING = /^<\\?xml\\s[^>]*?encoding\\s*=\\s*[\"']([\\w.-]+)[\"']/;\n// The grammar has no place for `[`, so a doctype with an internal subset does not match and is refused.\nconst DOCTYPE = new RegExp(`<!DOCTYPE\\\\s+${QNAME}(?:\\\\s+(?:SYSTEM\\\\s+${QUOTED}|PUBLIC\\\\s+${QUOTED}\\\\s+${QUOTED}))?\\\\s*>`, 'uy');\nconst END_TAG = new RegExp(`</(${QNAME})\\\\s*>`, 'uy');\nconst START_TAG = new RegExp(`<(${QNAME})((?:\\\\s+${QNAME}\\\\s*=\\\\s*(?:\"[^<\"]*\"|'[^<']*'))*)\\\\s*(/?)>`, 'uy');\nconst ATTRIBUTE = new RegExp(`(${QNAME})\\\\s*=\\\\s*(?:\"([^\"]*)\"|'([^']*)')`, 'gu');\nconst REFERENCE = /&[^;]*;?/g;\nconst NUMBERED = /^&#(?:x([0-9a-fA-F]{1,6})|([0-9]{1,7}));$/;\nconst XML_CHARACTER = /^[\\t\\n\\r\\u{20}-\\u{D7FF}\\u{E000}-\\u{FFFD}\\u{10000}-\\u{10FFFF}]$/u;\nconst FORBIDDEN = /[\\u0000-\\u0008\\u000B\\u000C\\u000E-\\u001F]/;\nconst UNPRINTABLE = /[\\p{C}\\s]+/gu;\nconst PREDEFINED: Readonly<Record<string, string>> = { '&': '&', '<': '<', '>': '>', '"': '\"', ''': \"'\" };\nconst NO_BINDINGS: ReadonlyMap<string, string> = new Map();\n\ninterface OpenElement {\n readonly name: string;\n /** The element's place among NZB-namespace ancestors, such as `nzb/file`; `?` stands for any other element. */\n readonly path: string;\n readonly bindings: ReadonlyMap<string, string>;\n}\n\ninterface Scan {\n readonly text: string;\n at: number;\n readonly open: OpenElement[];\n elements: number;\n doctype: boolean;\n /** Character data since the last tag. */\n words: string;\n files: number;\n segments: number;\n usable: number;\n metaType: string;\n readonly meta: Map<string, string>;\n}\n\nfunction sure(condition: unknown, why: string): asserts condition {\n if (!condition) throw new Error(`invalid:nzb ${why}`);\n}\n\nfunction decode(bytes: Uint8Array): string {\n const body = bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf ? bytes.subarray(3) : bytes;\n const label = ENCODING.exec(new TextDecoder('latin1').decode(body.subarray(0, 200)))?.[1] ?? 'utf-8';\n try {\n return new TextDecoder(label, { fatal: true }).decode(body);\n } catch {\n throw new Error('invalid:nzb it is not text in the encoding it declares');\n }\n}\n\nfunction reference(written: string): string {\n const known = PREDEFINED[written];\n if (known !== undefined) return known;\n const numbered = NUMBERED.exec(written);\n sure(numbered, 'it uses an entity other than the five XML defines');\n const code = numbered[1] === undefined ? Number(numbered[2]) : Number.parseInt(numbered[1], 16);\n sure(code <= 0x10ffff && XML_CHARACTER.test(String.fromCodePoint(code)), 'it names a character XML does not allow');\n return String.fromCodePoint(code);\n}\n\nconst resolve = (raw: string): string => raw.replace(REFERENCE, reference);\n\nfunction attributesOf(raw: string): Map<string, string> {\n const attributes = new Map<string, string>();\n for (const [, name, double, single] of raw.matchAll(ATTRIBUTE)) {\n sure(!attributes.has(name as string), 'an element repeats an attribute');\n attributes.set(name as string, resolve(double ?? (single as string)));\n }\n return attributes;\n}\n\nfunction bindingsOf(parent: ReadonlyMap<string, string>, attributes: ReadonlyMap<string, string>): ReadonlyMap<string, string> {\n const declared = [...attributes].filter(([name]) => name === 'xmlns' || name.startsWith('xmlns:')).map(([name, uri]) => [name.slice(6), uri] as const);\n return declared.length > 0 ? new Map([...parent, ...declared]) : parent;\n}\n\nconst ENTER: Readonly<Record<string, (scan: Scan, attributes: ReadonlyMap<string, string>) => void>> = {\n 'nzb/file': (scan) => {\n scan.files += 1;\n scan.segments = 0;\n },\n 'nzb/head/meta': (scan, attributes) => {\n scan.metaType = attributes.get('type') ?? '';\n },\n};\n\nconst LEAVE: Readonly<Record<string, (scan: Scan) => void>> = {\n 'nzb/file/segments/segment': (scan) => {\n if (scan.words.trim() !== '') scan.segments += 1;\n },\n 'nzb/file': (scan) => {\n if (scan.segments > 0) scan.usable += 1;\n },\n 'nzb/head/meta': (scan) => {\n if (!scan.meta.has(scan.metaType)) scan.meta.set(scan.metaType, scan.words);\n },\n};\n\nfunction leave(scan: Scan, element: OpenElement): void {\n LEAVE[element.path]?.(scan);\n scan.words = '';\n}\n\nfunction startTag(scan: Scan): void {\n START_TAG.lastIndex = scan.at;\n const tag = START_TAG.exec(scan.text);\n sure(tag, 'a tag is malformed');\n const name = tag[1] as string;\n const parent = scan.open.at(-1);\n sure(parent || scan.elements === 0, 'it has more than one root element');\n sure(scan.open.length < MAX_DEPTH, 'its elements nest too deeply');\n scan.elements += 1;\n sure(scan.elements <= MAX_ELEMENTS, 'it has too many elements');\n const attributes = attributesOf(tag[2] as string);\n const bindings = bindingsOf(parent?.bindings ?? NO_BINDINGS, attributes);\n const [first, second] = name.split(':') as [string, string | undefined];\n const namespace = bindings.get(second === undefined ? '' : first);\n sure(second === undefined || namespace !== undefined, 'an element uses a prefix that is not bound');\n const kind = namespace === NAMESPACE ? (second ?? first) : '?';\n const element: OpenElement = { name, path: parent ? `${parent.path}/${kind}` : kind, bindings };\n sure(parent || element.path === 'nzb', 'its root is not an nzb element in the NZB namespace');\n scan.words = '';\n ENTER[element.path]?.(scan, attributes);\n if (tag[3]) leave(scan, element);\n else scan.open.push(element);\n scan.at += tag[0].length;\n}\n\nfunction endTag(scan: Scan): void {\n END_TAG.lastIndex = scan.at;\n const tag = END_TAG.exec(scan.text);\n const element = scan.open.pop();\n sure(tag && element && tag[1] === element.name, 'an end tag does not match the element it closes');\n leave(scan, element);\n scan.at += tag[0].length;\n}\n\nfunction skipTo(scan: Scan, lead: number, close: string, why: string): string {\n const end = scan.text.indexOf(close, scan.at + lead);\n sure(end !== -1, why);\n const inside = scan.text.slice(scan.at + lead, end);\n scan.at = end + close.length;\n return inside;\n}\n\nfunction literal(scan: Scan): void {\n sure(scan.open.length > 0, 'it has text outside its root element');\n scan.words += skipTo(scan, 9, ']]>', 'a literal section is never closed');\n}\n\nfunction doctype(scan: Scan): void {\n sure(!scan.doctype && scan.elements === 0, 'its doctype is misplaced');\n DOCTYPE.lastIndex = scan.at;\n const declared = DOCTYPE.exec(scan.text);\n sure(declared, 'its doctype carries declarations of its own');\n scan.doctype = true;\n scan.at += declared[0].length;\n}\n\nfunction characters(scan: Scan): void {\n const next = scan.text.indexOf('<', scan.at);\n const end = next === -1 ? scan.text.length : next;\n const words = resolve(scan.text.slice(scan.at, end));\n sure(scan.open.length > 0 || words.trim() === '', 'it has text outside its root element');\n scan.words += words;\n scan.at = end;\n}\n\n/** Longest lead first: the first that matches at the cursor decides how the markup is read. */\nconst MARKUP: ReadonlyArray<readonly [string, (scan: Scan) => void]> = [\n ['<!--', (scan) => void skipTo(scan, 4, '-->', 'a comment is never closed')],\n ['<![CDATA[', literal],\n ['<!DOCTYPE', doctype],\n ['<!', () => sure(false, 'it declares entities or other markup')],\n ['<?', () => sure(false, 'it carries a processing instruction')],\n ['</', endTag],\n ['<', startTag],\n ['', characters],\n];\n\n/**\n * Validates one NZB document without handing it to an XML library: the shell runs\n * where there is no `DOMParser`, and a strict scanner cannot be talked into loading\n * a DTD or expanding an entity (NAP-NZB, Submission). Accepted is well-formed XML\n * within the shell's bounds whose root is `nzb` in the NZB namespace and which lists\n * at least one file with a segment. An external doctype is read past and never\n * fetched; an internal subset, any declaration, any entity beyond XML's five and any\n * processing instruction are refused.\n *\n * @param bytes - The document as it will be handed to the downloader.\n * @returns The number of files listed and a display name from the document's own title.\n * @throws `invalid:nzb` followed by plain words for what was wrong.\n * @example\n * ```ts\n * readNzbDocument(bytes); // { files: 2, name: 'Holiday film (2019)' }\n * ```\n */\nexport function readNzbDocument(bytes: Uint8Array): NzbDocument {\n sure(bytes.length <= NZB_LIMITS.maxNZBBytes, 'it is larger than the shell accepts');\n const text = decode(bytes);\n sure(!FORBIDDEN.test(text), 'it holds a character XML does not allow');\n const scan: Scan = { text, at: DECLARATION.exec(text)?.[0].length ?? 0, open: [], elements: 0, doctype: false, words: '', files: 0, segments: 0, usable: 0, metaType: '', meta: new Map() };\n while (scan.at < text.length) {\n const [, read] = MARKUP.find(([lead]) => text.startsWith(lead, scan.at)) as (typeof MARKUP)[number];\n read(scan);\n }\n sure(scan.open.length === 0, 'it ends before its elements are closed');\n sure(scan.usable > 0, 'it lists no file with segments');\n const title = (scan.meta.get('title') ?? scan.meta.get('name') ?? '').replace(UNPRINTABLE, ' ').trim().slice(0, MAX_NAME_LENGTH);\n return { files: scan.files, name: title || UNNAMED };\n}\n","import type { NamespacedStore } from '../persistence/store.js';\nimport { NZB_LIMITS, type NzbErrorCode } from './nzb-wire.js';\n\nconst STORE_KEY = 'nzb-replay:v1';\nconst UNCERTAIN = 'This may have been carried out; check the download, then ask again with the same operation key';\n\n/** What one mutation record is kept under (NAP-NZB, Mutation replay). */\nexport interface NzbReplayScope {\n readonly applet: string;\n /** The downloader's key in the shell. */\n readonly downloader: string;\n readonly operationKey: string;\n}\n\n/** How a mutation ended: the result it was answered with, or the error. */\nexport type NzbOutcome = { readonly result: Readonly<Record<string, unknown>> } | { readonly error: { readonly code: NzbErrorCode; readonly message: string } };\n\n/** What is already on record under an operation key. */\nexport interface NzbReplayHit {\n /** True when the record was reserved for a different operation or different parameters. */\n readonly conflict: boolean;\n readonly replayUntil: number;\n /** The recorded outcome; `outcome_unknown` while the attempt is unresolved. */\n readonly outcome: NzbOutcome;\n /** The job handles the outcome names, which the applet must still own to be given it. */\n readonly jobIds: readonly string[];\n}\n\n/** The durable mutation records behind `add` and `control`. */\nexport interface NzbReplay {\n /** Drops records past their time, except those still being carried out. */\n prune(): void;\n /** What is on record under a key, compared with the digest of the request now made. */\n find(scope: NzbReplayScope, digest: string): NzbReplayHit | undefined;\n /** Writes the reservation, before any effect outside the shell. */\n reserve(scope: NzbReplayScope, digest: string): void;\n /** Writes that the downloader is about to be told, so a shell that dies now leaves the outcome uncertain. */\n dispatched(scope: NzbReplayScope): void;\n /** Writes the outcome; resolves with the record's new `replayUntil`. */\n settle(scope: NzbReplayScope, outcome: NzbOutcome, jobIds: readonly string[]): number;\n /** Drops a reservation whose work ended before the downloader was told anything. */\n release(scope: NzbReplayScope): void;\n /** Every job handle the applet's records still name. */\n referenced(applet: string): ReadonlySet<string>;\n}\n\ninterface ReplayRecord {\n readonly applet: string;\n /** SHA-256 of the operation and its exact parameters; the parameters themselves are not kept. */\n readonly digest: string;\n readonly replayUntil: number;\n readonly dispatched: boolean;\n readonly jobIds: readonly string[];\n readonly outcome?: NzbOutcome;\n}\n\ntype Loose = Readonly<Record<string, unknown>>;\n\nconst isObject = (value: unknown): value is Loose => typeof value === 'object' && value !== null;\nconst isText = (value: unknown): boolean => typeof value === 'string';\n\nfunction soundOutcome(outcome: unknown): boolean {\n if (outcome === undefined) return true;\n if (!isObject(outcome)) return false;\n return isObject(outcome.result) || (isObject(outcome.error) && isText(outcome.error.code) && isText(outcome.error.message));\n}\n\nfunction sound(record: unknown): record is ReplayRecord {\n if (!isObject(record) || !Array.isArray(record.jobIds)) return false;\n return isText(record.applet) && isText(record.digest) && Number.isSafeInteger(record.replayUntil) && typeof record.dispatched === 'boolean' && record.jobIds.every(isText) && soundOutcome(record.outcome);\n}\n\n/**\n * The digest a mutation record is compared by: SHA-256 over the operation and its\n * validated parameters with object members in a fixed order, so member order does not\n * matter and nothing else is normalised (NAP-NZB, Mutation replay). The record keeps\n * only this digest, never the document or a password.\n *\n * @param operation - `add` or `control`.\n * @param request - The validated request, exactly as the applet sent it.\n * @returns Lowercase hexadecimal SHA-256.\n * @example\n * ```ts\n * await digestNzbRequest('control', { jobId, operationKey: 'pause-1', action: 'pause' });\n * ```\n */\nexport async function digestNzbRequest(operation: string, request: unknown): Promise<string> {\n const ordered = (_key: string, value: unknown): unknown => (isObject(value) ? Object.fromEntries(Object.entries(value).sort(([left], [right]) => (left < right ? -1 : 1))) : value);\n const hash = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(JSON.stringify({ operation, request }, ordered)));\n return Array.from(new Uint8Array(hash), (byte) => byte.toString(16).padStart(2, '0')).join('');\n}\n\n/**\n * The mutation records over the shell's store. A record is written before anything\n * outside the shell is touched and again before the downloader is told, so a shell\n * that dies in between finds a record with no outcome when it comes back and answers\n * `outcome_unknown` instead of sending the change a second time.\n *\n * @param store - The shell's namespaced store.\n * @param now - Whole seconds since the epoch.\n * @returns The replay records.\n * @example\n * ```ts\n * const replay = createNzbReplay(store, () => Math.floor(Date.now() / 1000));\n * replay.find({ applet: 'reader', downloader: 'nzbget', operationKey: 'add-1' }, digest); // undefined\n * ```\n */\nexport function createNzbReplay(store: NamespacedStore, now: () => number): NzbReplay {\n /** Records this shell is carrying out now; anything else without an outcome was left by a shell that is gone. */\n const active = new Map<string, ReplayRecord>();\n const keyOf = (scope: NzbReplayScope): string => JSON.stringify([scope.applet, scope.downloader, scope.operationKey]);\n const load = (): Map<string, ReplayRecord> => new Map(Object.entries(store.getJson<Loose | null>(STORE_KEY, null) ?? {}).filter((entry): entry is [string, ReplayRecord] => sound(entry[1])));\n const write = (key: string, record: ReplayRecord | undefined): void => {\n const records = load();\n if (record) records.set(key, record);\n else records.delete(key);\n store.setJson(STORE_KEY, Object.fromEntries(records));\n };\n const later = (replayUntil: number): number => Math.max(replayUntil, now() + NZB_LIMITS.replaySeconds);\n const advance = (key: string, change: Partial<ReplayRecord>): ReplayRecord => {\n const record = { ...(active.get(key) as ReplayRecord), ...change };\n active.set(key, record);\n write(key, record);\n return record;\n };\n const orphan = (key: string, record: ReplayRecord): ReplayRecord | undefined => {\n const left = record.dispatched ? { ...record, replayUntil: later(record.replayUntil), outcome: { error: { code: 'outcome_unknown' as const, message: UNCERTAIN } } } : undefined;\n write(key, left);\n return left;\n };\n return {\n prune() {\n const records = load();\n const kept = [...records].filter(([key, record]) => record.replayUntil > now() || active.has(key));\n if (kept.length < records.size) store.setJson(STORE_KEY, Object.fromEntries(kept));\n },\n find(scope, digest) {\n const key = keyOf(scope);\n const stored = load().get(key);\n const record = stored && !stored.outcome && !active.has(key) ? orphan(key, stored) : stored;\n if (!record) return undefined;\n const outcome = record.outcome ?? { error: { code: 'outcome_unknown', message: UNCERTAIN } };\n return { conflict: record.digest !== digest, replayUntil: record.replayUntil, outcome, jobIds: record.jobIds };\n },\n reserve(scope, digest) {\n const key = keyOf(scope);\n active.set(key, { applet: scope.applet, digest, replayUntil: later(0), dispatched: false, jobIds: [] });\n advance(key, {});\n },\n dispatched: (scope) => void advance(keyOf(scope), { dispatched: true }),\n settle(scope, outcome, jobIds) {\n const key = keyOf(scope);\n const { replayUntil } = advance(key, { outcome, jobIds, replayUntil: later((active.get(key) as ReplayRecord).replayUntil) });\n active.delete(key);\n return replayUntil;\n },\n release(scope) {\n active.delete(keyOf(scope));\n write(keyOf(scope), undefined);\n },\n referenced: (applet) => new Set([...load().values()].filter((record) => record.applet === applet).flatMap((record) => record.jobIds)),\n };\n}\n","import { NZB_ACTIONS, NZB_LIMITS, need, type NzbAddRequest, type NzbControlRequest, type NzbJobsRequest } from './nzb-wire.js';\n\nconst MAX_TEXT_LENGTH = 1024;\nconst MAX_URL_LENGTH = 4096;\nconst MISSHAPEN = 'The request is not shaped as NAP-NZB describes';\n// RFC 4648 section 4 with padding; the last character before `=` may carry no stray bits. Checked in two\n// parts because one pattern over a whole document of several megabytes overruns the regular expression stack.\nconst NOT_BASE64 = /[^A-Za-z0-9+/]/;\nconst LAST_QUAD = /^(?:[A-Za-z0-9+/]{4}|[A-Za-z0-9+/][AQgw]==|[A-Za-z0-9+/]{2}[AEIMQUYcgkosw048]=)?$/;\n// Absolute https with a host, no userinfo, no fragment and no whitespace.\nconst HTTPS_URL = /^https:\\/\\/[^/?#@\\s]+(?:[/?][^#\\s]*)?$/i;\n\ntype Check = (value: unknown) => boolean;\ntype Loose = Readonly<Record<string, unknown>>;\n\nconst text: Check = (value) => typeof value === 'string' && value !== '';\nconst flag: Check = (value) => typeof value === 'boolean';\nconst count =\n (least: number): Check =>\n (value) =>\n Number.isSafeInteger(value) && (value as number) >= least;\nconst oneOf =\n (choices: readonly string[]): Check =>\n (value) =>\n choices.includes(value as string);\nconst base64: Check = (value) => typeof value === 'string' && value.length % 4 === 0 && !NOT_BASE64.test(value.slice(0, -4)) && LAST_QUAD.test(value.slice(-4));\nconst isObject = (value: unknown): value is Loose => typeof value === 'object' && value !== null && !Array.isArray(value);\n\nfunction shaped(value: unknown, required: Readonly<Record<string, Check>>, optional: Readonly<Record<string, Check>> = {}): boolean {\n if (!isObject(value)) return false;\n const checks = new Map([...Object.entries(required), ...Object.entries(optional)]);\n return Object.keys(required).every((field) => Object.hasOwn(value, field)) && Object.entries(value).every(([field, held]) => checks.get(field)?.(held) === true);\n}\n\nfunction read<T>(value: unknown, required: Readonly<Record<string, Check>>, optional?: Readonly<Record<string, Check>>): T {\n need(shaped(value, required, optional), 'invalid_request', MISSHAPEN);\n need(Object.values(value as Loose).every((held) => typeof held !== 'string' || held.length <= MAX_TEXT_LENGTH), 'limit_exceeded', 'A text value is longer than the shell accepts');\n return value as T;\n}\n\nconst source: Check = (value) =>\n shaped(value, { kind: (kind) => kind === 'bytes', dataBase64: base64 }) ||\n shaped(value, { kind: (kind) => kind === 'url', url: (url) => text(url) && (url as string).length <= MAX_URL_LENGTH && HTTPS_URL.test(url as string) && URL.canParse(url as string) });\n\nconst page = { after: text, limit: count(1) };\n\n/** How each NAP-NZB request type carries its parameters beside `type` and `id`. */\nconst ENVELOPES: Readonly<Record<string, Readonly<Record<string, Check>>>> = {\n 'nzb.downloaders': {},\n 'nzb.add': { request: isObject },\n 'nzb.jobs': { request: isObject },\n 'nzb.status': { jobId: text },\n 'nzb.control': { request: isObject },\n 'nzb.files': { request: isObject },\n 'nzb.read': { request: isObject },\n};\n\n/**\n * Every inbound NAP-NZB message type.\n *\n * @example\n * ```ts\n * NZB_REQUEST_TYPES.includes('nzb.add'); // true\n * ```\n */\nexport const NZB_REQUEST_TYPES: readonly string[] = Object.keys(ENVELOPES);\n\n/**\n * Checks a message's envelope and takes out what it carries: nothing for\n * `nzb.downloaders`, `jobId` for `nzb.status`, `request` for the rest. A field the\n * type does not have is `invalid_request` (NAP-NZB, Common values).\n *\n * @param message - The message as received, of a type in {@link NZB_REQUEST_TYPES}.\n * @returns The payload, still unchecked beyond being an object or nonempty text.\n * @example\n * ```ts\n * readNzbEnvelope({ type: 'nzb.status', id: 's1', jobId: 'job-a' }); // 'job-a'\n * ```\n */\nexport function readNzbEnvelope(message: { readonly type: string }): unknown {\n const fields = message as Loose;\n need(shaped(fields, { type: text, id: text, ...ENVELOPES[message.type] }), 'invalid_request', MISSHAPEN);\n return fields.request ?? fields.jobId;\n}\n\n/**\n * Checks an `AddRequest`: every field known and of its type, base64 canonical, an\n * address absolute `https` with no userinfo and no fragment.\n *\n * @param request - The request as received.\n * @returns The same object, typed.\n * @example\n * ```ts\n * readNzbAdd({ downloaderId, operationKey: 'add-1', source: { kind: 'bytes', dataBase64 } });\n * ```\n */\nexport function readNzbAdd(request: unknown): NzbAddRequest {\n return read(request, { downloaderId: text, operationKey: text, source }, { name: text, categoryId: text, priority: oneOf(['low', 'normal', 'high']), startPaused: flag, password: text });\n}\n\n/**\n * Checks a `JobsRequest` and settles its page size.\n *\n * @param request - The request as received.\n * @returns The request with `limit` filled in; a limit above the advertised page size is `limit_exceeded`.\n * @example\n * ```ts\n * readNzbJobs({ downloaderId }).limit; // 100\n * ```\n */\nexport function readNzbJobs(request: unknown): Required<Pick<NzbJobsRequest, 'downloaderId' | 'limit'>> & Pick<NzbJobsRequest, 'after'> {\n const jobs = read<NzbJobsRequest>(request, { downloaderId: text }, page);\n const limit = jobs.limit ?? NZB_LIMITS.maxPageSize;\n need(limit <= NZB_LIMITS.maxPageSize, 'limit_exceeded', 'That is more jobs than the shell lists at a time');\n return { ...jobs, limit };\n}\n\n/**\n * Checks a `ControlRequest`.\n *\n * @param request - The request as received.\n * @returns The same object, typed.\n * @example\n * ```ts\n * readNzbControl({ jobId, operationKey: 'pause-1', action: 'pause' });\n * ```\n */\nexport function readNzbControl(request: unknown): NzbControlRequest {\n return read(request, { jobId: text, operationKey: text, action: oneOf(NZB_ACTIONS) });\n}\n\n/**\n * Checks a `FilesRequest` or, with `reading`, a `ReadRequest`. kernl cannot read a\n * downloader's files, so only the job named matters afterwards.\n *\n * @param request - The request as received.\n * @param reading - Whether this is `nzb.read`.\n * @returns The job handle the request names.\n * @example\n * ```ts\n * readNzbFiles({ jobId: 'job-a' }, false); // 'job-a'\n * ```\n */\nexport function readNzbFiles(request: unknown, reading: boolean): string {\n const checked = reading ? read<{ jobId: string }>(request, { jobId: text, fileId: text, offset: count(0), length: count(1) }) : read<{ jobId: string }>(request, { jobId: text }, page);\n return checked.jobId;\n}\n\n/**\n * Decodes canonical base64 that {@link readNzbAdd} already checked.\n *\n * @param data - Standard padded base64.\n * @returns The decoded bytes.\n * @example\n * ```ts\n * decodeNzbBase64('PG56Yi8+'); // the bytes of '<nzb/>'\n * ```\n */\nexport function decodeNzbBase64(data: string): Uint8Array {\n return Uint8Array.from(atob(data), (character) => character.charCodeAt(0));\n}\n","import type { NzbClient, NzbClientJob } from '@kernlize/bridges';\nimport type { DownloadServiceDeps } from './types.js';\nimport type { NzbHandles, NzbJobHandle } from './nzb-handles.js';\nimport type { NzbReplay } from './nzb-replay.js';\nimport { need, NzbFault, type NzbErrorCode, type NzbJob } from './nzb-wire.js';\n\n/** One downloader the person set up. */\nexport interface NzbDownloader {\n /**\n * What handles are issued against; never sent to an applet. The shell passes the connection's\n * routing key, which changes with its address, so a handle issued for one server's job never\n * reaches another server's job with the same id.\n */\n readonly key: string;\n /** What the person calls it. */\n readonly label: string;\n readonly client: NzbClient;\n}\n\n/** What the NZB service needs from the shell. */\nexport interface NzbServiceOptions extends DownloadServiceDeps {\n /** The downloaders the person set up, read on every request. */\n readonly downloaders: () => readonly NzbDownloader[];\n /** Fetches an NZB for a `url` source under the shell's own fetch policy; without it only `bytes` is offered. */\n readonly fetchDocument?: (url: string, signal: AbortSignal) => Promise<Uint8Array>;\n}\n\n/** One request being answered: whose it is, and whether its answer is still wanted. */\nexport interface NzbCall {\n readonly windowId: string;\n /** The applet's stable name, which handles and records are scoped to. */\n readonly applet: string;\n /** False once the window closed, lost the domain or runs another applet; checked again before every effect. */\n readonly live: () => boolean;\n}\n\n/** What every NZB operation works with. */\nexport interface NzbSession {\n readonly options: NzbServiceOptions;\n /** Whole seconds since the epoch. */\n readonly now: () => number;\n readonly handles: NzbHandles;\n readonly replay: NzbReplay;\n /** Aborted when the service is torn down. */\n readonly signal: AbortSignal;\n /** Runs work after everything queued earlier under the same name, so changes to one job take turns. */\n readonly inTurn: <T>(lane: string, work: () => Promise<T>) => Promise<T>;\n}\n\n/** A job handle together with the downloader it lives on. */\nexport interface NzbOwnedJob {\n readonly handle: NzbJobHandle;\n readonly downloader: NzbDownloader;\n}\n\ninterface Failure {\n readonly reason: string;\n readonly code: NzbErrorCode;\n readonly message: string;\n /** Whether, once a change was sent, this failure leaves open that it was applied. */\n readonly uncertain?: true;\n}\n\nconst UNSURE = 'This may have been carried out; check the download, then ask again with the same operation key';\n\n/** {@link import('@kernlize/bridges').ClientFailure} reasons as NAP-NZB errors, in words that name no address, path or id. */\nconst FAILURES: readonly Failure[] = [\n { reason: 'denied:credentials', code: 'authentication_required', message: 'The downloader refused the sign-in the shell holds for it' },\n { reason: 'unavailable:unreachable', code: 'unavailable', message: 'The downloader could not be reached' },\n { reason: 'unavailable:timeout', code: 'unavailable', message: 'The downloader did not answer in time', uncertain: true },\n { reason: 'unavailable:rejected', code: 'backend_rejected', message: 'The downloader declined' },\n { reason: 'unavailable:not-found', code: 'not_found', message: 'The downloader has no such download' },\n { reason: 'unavailable:unsupported', code: 'unsupported', message: 'The downloader cannot do that' },\n { reason: 'unavailable:outcome-unknown', code: 'outcome_unknown', message: UNSURE },\n { reason: 'invalid:state', code: 'invalid_state', message: 'The download is no longer in a state where that applies' },\n { reason: 'invalid:', code: 'backend_rejected', message: 'The downloader declined' },\n { reason: '', code: 'backend_error', message: 'The request could not be completed', uncertain: true },\n];\n\n/**\n * Turns whatever an operation threw into the error an applet is sent. An adapter's\n * failure is read by its stable reason and never quoted. Once a change has been sent,\n * a missing or unreadable acknowledgement is `outcome_unknown`, never a claim that\n * nothing happened (NAP-NZB, Error Handling).\n *\n * @param error - What was thrown.\n * @param sent - Whether a change had been sent to the downloader.\n * @returns The fault to answer with.\n * @example\n * ```ts\n * nzbFaultOf(new Error('unavailable:timeout'), true).code; // 'outcome_unknown'\n * ```\n */\nexport function nzbFaultOf(error: unknown, sent: boolean): NzbFault {\n if (error instanceof NzbFault) return error;\n const reason = error instanceof Error ? error.message : '';\n const failure = FAILURES.find((row) => reason.startsWith(row.reason)) as Failure;\n return sent && failure.uncertain ? new NzbFault('outcome_unknown', UNSURE) : new NzbFault(failure.code, failure.message);\n}\n\n/**\n * The downloaders the person set up, each key once: a key names one server, so a\n * second downloader under a key already seen is not offered.\n *\n * @param session - The service's session.\n * @returns The downloaders, first of each key.\n * @example\n * ```ts\n * nzbDownloaders(session).map((downloader) => downloader.label); // ['Home']\n * ```\n */\nexport function nzbDownloaders(session: NzbSession): readonly NzbDownloader[] {\n return session.options.downloaders().filter((downloader, index, all) => all.findIndex((other) => other.key === downloader.key) === index);\n}\n\n/**\n * The downloader an applet's handle stands for.\n *\n * @param session - The service's session.\n * @param applet - The applet asking.\n * @param downloaderId - The handle it sent.\n * @returns The downloader; `not_found` when the handle is not this applet's or the downloader is no longer set up.\n * @example\n * ```ts\n * nzbDownloaderOf(session, 'reader', downloaderId).label; // 'Home'\n * ```\n */\nexport function nzbDownloaderOf(session: NzbSession, applet: string, downloaderId: string): NzbDownloader {\n const key = session.handles.downloaderKey(applet, downloaderId);\n const downloader = nzbDownloaders(session).find((candidate) => candidate.key === key);\n need(downloader, 'not_found', 'No such downloader');\n return downloader;\n}\n\n/**\n * The job an applet's handle stands for, which may be one the downloader no longer has.\n * A job another applet or the person added has no handle here, so it is concealed.\n *\n * @param session - The service's session.\n * @param applet - The applet asking.\n * @param jobId - The handle it sent.\n * @returns The handle and its downloader; `not_found` otherwise.\n * @example\n * ```ts\n * nzbJobOf(session, 'reader', jobId).handle.gone; // false\n * ```\n */\nexport function nzbJobOf(session: NzbSession, applet: string, jobId: string): NzbOwnedJob {\n const handle = session.handles.job(applet, jobId);\n const downloader = nzbDownloaders(session).find((candidate) => candidate.key === handle?.key);\n need(handle && downloader, 'not_found', 'No such download');\n return { handle, downloader };\n}\n\n/**\n * One observation of a job in NAP-NZB's shape. kernl is a remote control, so\n * `canReadFiles` is always false; fields the downloader did not report are left out.\n *\n * @param session - The service's session.\n * @param owned - The applet's handle and the downloader.\n * @param job - What the downloader reported just now.\n * @returns The `Job`.\n * @example\n * ```ts\n * describeNzbJob(session, owned, await owned.downloader.client.get(owned.handle.backend));\n * ```\n */\nexport function describeNzbJob(session: NzbSession, owned: NzbOwnedJob, job: NzbClientJob): NzbJob {\n const { handle, downloader } = owned;\n const optional = {\n categoryId: job.category === undefined ? undefined : session.handles.categoryId(handle.applet, handle.key, job.category),\n downloadPaused: job.paused,\n downloadProgress: job.progress,\n downloadedBytes: job.downloadedBytes,\n totalBytes: job.totalBytes,\n downloadRate: job.downloadRate,\n stage: job.stage,\n message: job.message,\n };\n return {\n jobId: handle.id,\n downloaderId: session.handles.downloaderId(handle.applet, handle.key),\n name: job.name,\n state: job.state,\n observedAt: session.now(),\n actions: job.actions.filter((action) => downloader.client.actions.includes(action)),\n canReadFiles: false,\n ...Object.fromEntries(Object.entries(optional).filter(([, value]) => value !== undefined)),\n };\n}\n\n/**\n * A fresh look at one job. A job the downloader answers for no longer is marked gone,\n * so its handle is never bound to whatever the downloader numbers the same way later\n * (NAP-NZB, Common values); a downloader that does not answer leaves the handle alone.\n *\n * @param session - The service's session.\n * @param owned - The applet's handle and the downloader.\n * @returns What the downloader reports; `not_found` once it has no such job.\n * @example\n * ```ts\n * const job = await observeNzbJob(session, nzbJobOf(session, 'reader', jobId));\n * ```\n */\nexport async function observeNzbJob(session: NzbSession, owned: NzbOwnedJob): Promise<NzbClientJob> {\n need(!owned.handle.gone, 'not_found', 'No such download');\n const seen = await owned.downloader.client.get(owned.handle.backend);\n if (!seen) session.handles.retire(owned.handle.applet, owned.handle.id);\n need(seen, 'not_found', 'No such download');\n return seen;\n}\n","import type { NzbClientAdd, NzbClientJob } from '@kernlize/bridges';\nimport { readNzbDocument, type NzbDocument } from './nzb-document.js';\nimport { digestNzbRequest, type NzbReplayHit, type NzbReplayScope } from './nzb-replay.js';\nimport { decodeNzbBase64, readNzbAdd, readNzbControl } from './nzb-requests.js';\nimport { describeNzbJob, observeNzbJob, nzbDownloaderOf, nzbFaultOf, nzbJobOf, type NzbCall, type NzbDownloader, type NzbOwnedJob, type NzbSession } from './nzb-session.js';\nimport { need, NZB_LIMITS, NzbFault, type NzbAddOption, type NzbAddRequest, type NzbAddResult, type NzbControlRequest, type NzbControlResult, type NzbJobAction } from './nzb-wire.js';\n\nconst FETCH_DEADLINE_MS = 30_000;\nconst TERMINAL: readonly string[] = ['completed', 'failed', 'cancelled', 'skipped'];\nconst ADD_OPTIONS: readonly NzbAddOption[] = ['categoryId', 'priority', 'startPaused', 'password'];\nconst REVOKED = 'This applet may no longer use downloads';\n\n/** What a mutation hands back when it worked: the result without its replay boundary, and the job handles it names. */\ninterface Done<R> {\n readonly result: Omit<R, 'replayUntil'>;\n readonly jobIds: readonly string[];\n}\n\n/** One mutation: its record's scope, what it is compared by, the checks that leave no record, and the work itself. */\ninterface Mutation<R, P> {\n readonly scope: NzbReplayScope;\n readonly operation: 'add' | 'control';\n readonly request: unknown;\n /** Everything that can be refused before a record is reserved; nothing here reaches outside the shell with a change. */\n readonly prepare: () => Promise<P>;\n /** The work; `sending` is called the moment before the downloader is told. */\n readonly run: (prepared: P, sending: () => void) => Promise<Done<R>>;\n}\n\nfunction replayed<R>(session: NzbSession, applet: string, hit: NzbReplayHit): R {\n if (hit.conflict) throw new NzbFault('conflict', 'This operation key was already used for a different request', hit.replayUntil);\n if ('error' in hit.outcome) throw new NzbFault(hit.outcome.error.code, hit.outcome.error.message, hit.replayUntil);\n // NAP-NZB, Mutation replay: a recorded success is authorised again before it is delivered.\n need(\n hit.jobIds.every((jobId) => session.handles.job(applet, jobId)),\n 'permission_denied',\n 'This download is no longer this applet’s',\n );\n return { ...hit.outcome.result, replayUntil: hit.replayUntil } as R;\n}\n\n/**\n * Carries out one mutation under its replay record (NAP-NZB, Mutation replay). The\n * key is looked up and reserved in one step with nothing awaited in between, so the\n * same request arriving twice is sent once. Work that ends before the downloader was\n * told anything gives the key back; anything after that is recorded, error or not.\n */\nasync function mutate<R, P>(session: NzbSession, mutation: Mutation<R, P>): Promise<R> {\n const { scope } = mutation;\n const digest = await digestNzbRequest(mutation.operation, mutation.request);\n session.replay.prune();\n session.handles.forget(scope.applet, session.replay.referenced(scope.applet));\n const earlier = session.replay.find(scope, digest);\n if (earlier) return replayed(session, scope.applet, earlier);\n const prepared = await mutation.prepare();\n const meanwhile = session.replay.find(scope, digest);\n if (meanwhile) return replayed(session, scope.applet, meanwhile);\n session.replay.reserve(scope, digest);\n let sent = false;\n const sending = (): void => {\n session.replay.dispatched(scope);\n sent = true;\n };\n try {\n const done = await mutation.run(prepared, sending);\n return { ...done.result, replayUntil: session.replay.settle(scope, { result: done.result }, done.jobIds) } as R;\n } catch (error) {\n const { code, message } = nzbFaultOf(error, sent);\n if (sent) throw new NzbFault(code, message, session.replay.settle(scope, { error: { code, message } }, []));\n session.replay.release(scope);\n throw new NzbFault(code, message);\n }\n}\n\ninterface Checked {\n readonly bytes: Uint8Array;\n readonly document: NzbDocument;\n}\n\nfunction checkDocument(bytes: Uint8Array): Checked {\n need(bytes.length <= NZB_LIMITS.maxNZBBytes, 'limit_exceeded', 'The NZB document is larger than the shell accepts');\n try {\n return { bytes, document: readNzbDocument(bytes) };\n } catch (error) {\n throw new NzbFault('invalid_request', `The NZB document was not accepted: ${(error as Error).message.slice('invalid:nzb '.length)}`);\n }\n}\n\ninterface AddPlan {\n /** The downloader's own name for the chosen category, and the label the person knows it by. */\n readonly category?: string;\n /** Present for a `bytes` source, which is checked before anything is reserved. */\n readonly checked?: Checked;\n}\n\nasync function planAdd(session: NzbSession, call: NzbCall, downloader: NzbDownloader, request: NzbAddRequest): Promise<AddPlan> {\n const { client } = downloader;\n need(request.source.kind === 'bytes' || session.options.fetchDocument, 'unsupported', 'This downloader takes NZB documents as bytes only');\n need(\n ADD_OPTIONS.every((option) => request[option] === undefined || client.addOptions.includes(option)),\n 'unsupported',\n 'This downloader cannot honour one of the options asked for',\n );\n const category = request.categoryId === undefined ? undefined : session.handles.categoryName(call.applet, downloader.key, request.categoryId);\n need(request.categoryId === undefined || category !== undefined, 'not_found', 'No such category');\n // NAP-NZB, Submission: an unknown category is never swapped for another, so one the downloader has since dropped is refused.\n if (category !== undefined) need((await client.categories()).some((offered) => offered.name === category), 'not_found', 'No such category');\n if (request.source.kind === 'url') return category === undefined ? {} : { category };\n const encoded = request.source.dataBase64;\n need(encoded.length <= Math.ceil(NZB_LIMITS.maxNZBBytes / 3) * 4, 'limit_exceeded', 'The NZB document is larger than the shell accepts');\n return { ...(category === undefined ? {} : { category }), checked: checkDocument(decodeNzbBase64(encoded)) };\n}\n\nasync function fetched(session: NzbSession, url: string): Promise<Checked> {\n const fetchDocument = session.options.fetchDocument as NonNullable<NzbSession['options']['fetchDocument']>;\n // The address may carry a token in its query, so neither it nor the fetcher's own words go any further.\n const bytes = await fetchDocument(url, AbortSignal.any([session.signal, AbortSignal.timeout(FETCH_DEADLINE_MS)])).catch(() => {\n throw new NzbFault('unavailable', 'The NZB document could not be fetched');\n });\n return checkDocument(bytes);\n}\n\n/**\n * `nzb.add`: hands one NZB document to one downloader after the person said yes.\n * The document is validated before the downloader sees it, the person is told the\n * download carries on in that program after the applet is closed, and a no leaves\n * neither a job nor a record.\n *\n * @param session - The service's session.\n * @param call - Whose request this is.\n * @param raw - The `AddRequest` as received.\n * @returns The `AddResult`.\n * @example\n * ```ts\n * const { job, replayUntil } = await addNzb(session, call, { downloaderId, operationKey: 'add-1', source });\n * ```\n */\nexport async function addNzb(session: NzbSession, call: NzbCall, raw: unknown): Promise<NzbAddResult> {\n const request = readNzbAdd(raw);\n const downloader = nzbDownloaderOf(session, call.applet, request.downloaderId);\n const { client, key, label } = downloader;\n const run = async (plan: AddPlan, sending: () => void): Promise<Done<NzbAddResult>> => {\n const { bytes, document } = plan.checked ?? (await fetched(session, (request.source as { url: string }).url));\n const name = request.name ?? document.name;\n const lines = [\n { label: 'Name', value: name },\n { label: 'Files', value: document.files === 1 ? '1 file' : `${document.files} files` },\n ...(plan.category === undefined ? [] : [{ label: 'Category', value: plan.category }]),\n { label: 'Keeps going', value: `This download carries on in ${label} after this applet is closed` },\n ];\n need(await session.options.ask(call.windowId, { kind: 'add', title: `Add an NZB job to ${label}`, lines }), 'permission_denied', 'The person declined this download');\n need(call.live(), 'permission_denied', REVOKED);\n const submission: NzbClientAdd = {\n bytes,\n name,\n ...(plan.category === undefined ? {} : { category: plan.category }),\n ...(request.priority === undefined ? {} : { priority: request.priority }),\n ...(request.startPaused === undefined ? {} : { paused: request.startPaused }),\n ...(request.password === undefined ? {} : { password: request.password }),\n };\n sending();\n const { id } = await client.add(submission);\n const handle = { applet: call.applet, id: session.handles.jobId(call.applet, key, id), key, backend: id, gone: false };\n // The job is identified, so it is reported even when it cannot be looked at yet: as `unknown`, never as a guess.\n const seen = (await client.get(id).catch(() => undefined)) ?? ({ id, name, state: 'unknown', actions: [] } satisfies NzbClientJob);\n return { result: { job: describeNzbJob(session, { handle, downloader }, seen) }, jobIds: [handle.id] };\n };\n return mutate(session, { scope: { applet: call.applet, downloader: key, operationKey: request.operationKey }, operation: 'add', request, prepare: () => planAdd(session, call, downloader, request), run });\n}\n\n/** NAP-NZB, Job control: a hold already set or cleared satisfies pause or resume without new work in the downloader. */\nfunction alreadyHeld(job: NzbClientJob, action: NzbJobAction): boolean {\n return !TERMINAL.includes(job.state) && ((action === 'pause' && job.paused === true) || (action === 'resume' && job.paused === false));\n}\n\nasync function applyControl(session: NzbSession, call: NzbCall, owned: NzbOwnedJob, request: NzbControlRequest, sending: () => void): Promise<Done<NzbControlResult>> {\n const { handle, downloader } = owned;\n const { jobId, action } = request;\n const stale = 'That no longer applies to this download';\n let seen = await observeNzbJob(session, owned);\n if (alreadyHeld(seen, action)) return { result: { jobId, action, job: describeNzbJob(session, owned, seen) }, jobIds: [jobId] };\n need(seen.actions.includes(action), 'invalid_state', stale);\n if (action === 'delete') {\n const lines = [\n { label: 'Name', value: seen.name },\n { label: 'Erases', value: `The files this download saved, and its record in ${downloader.label}` },\n ];\n need(await session.options.ask(call.windowId, { kind: 'delete', title: `Erase a download from ${downloader.label}`, lines }), 'permission_denied', 'Deleting download data is not authorized');\n seen = await observeNzbJob(session, owned);\n need(seen.actions.includes(action), 'invalid_state', stale);\n }\n need(call.live(), 'permission_denied', REVOKED);\n sending();\n const { id } = await downloader.client.control(handle.backend, action);\n if (action === 'forget' || action === 'delete') {\n session.handles.retire(handle.applet, handle.id);\n return { result: { jobId, action }, jobIds: [jobId] };\n }\n const after = await downloader.client.get(id).catch(() => undefined);\n need(after, 'outcome_unknown', 'The downloader took the request, but the download could not be seen afterwards');\n // A retry may make a successor; it gets a handle of its own and the original's is left as it was.\n const successor = id === handle.backend ? handle : { ...handle, id: session.handles.jobId(handle.applet, handle.key, id), backend: id };\n return { result: { jobId, action, job: describeNzbJob(session, { handle: successor, downloader }, after) }, jobIds: [jobId, successor.id] };\n}\n\n/**\n * `nzb.control`: one action on one job the applet submitted. Changes to one job take\n * turns, the job is looked at again before anything is sent, and `delete` asks the\n * person first because it erases files.\n *\n * @param session - The service's session.\n * @param call - Whose request this is.\n * @param raw - The `ControlRequest` as received.\n * @returns The `ControlResult`.\n * @example\n * ```ts\n * await controlNzb(session, call, { jobId, operationKey: 'pause-1', action: 'pause' });\n * ```\n */\nexport async function controlNzb(session: NzbSession, call: NzbCall, raw: unknown): Promise<NzbControlResult> {\n const request = readNzbControl(raw);\n const owned = nzbJobOf(session, call.applet, request.jobId);\n const { handle, downloader } = owned;\n return mutate(session, {\n scope: { applet: call.applet, downloader: downloader.key, operationKey: request.operationKey },\n operation: 'control',\n request,\n // A job that is gone still answers a replay of what was done to it, so this is checked only for a new key.\n prepare: async () => {\n need(!handle.gone, 'not_found', 'No such download');\n need(downloader.client.actions.includes(request.action), 'unsupported', 'This downloader cannot do that');\n },\n run: (_prepared, sending) => session.inTurn(`${handle.key}\\n${handle.backend}`, () => applyControl(session, call, owned, request, sending)),\n });\n}\n","import { readNzbFiles, readNzbJobs } from './nzb-requests.js';\nimport { describeNzbJob, nzbDownloaderOf, nzbDownloaders, nzbJobOf, observeNzbJob, type NzbCall, type NzbDownloader, type NzbSession } from './nzb-session.js';\nimport { need, NZB_LIMITS, NzbFault, type NzbDownloaderInfo, type NzbDownloadersResult, type NzbJob, type NzbJobsResult } from './nzb-wire.js';\n\nconst encoder = new TextEncoder();\n/** A string whose code units are the text's UTF-8 bytes, so plain comparison is byte order (NAP-NZB, Jobs and state). */\nconst byteOrder = (text: string): string => String.fromCharCode(...encoder.encode(text));\n\n/**\n * `nzb.downloaders`: what each downloader the person set up can do, under a handle\n * that is this applet's alone. A downloader that does not answer is still listed, with\n * no categories; its trouble is reported when something is asked of it.\n *\n * @param session - The service's session.\n * @param call - Whose request this is.\n * @returns The `DownloadersResult`.\n * @example\n * ```ts\n * (await describeNzbDownloaders(session, call)).downloaders[0]?.canReadFiles; // false\n * ```\n */\nexport async function describeNzbDownloaders(session: NzbSession, call: NzbCall): Promise<NzbDownloadersResult> {\n const { handles, options } = session;\n const describe = async ({ client, key, label }: NzbDownloader): Promise<NzbDownloaderInfo> => {\n const offered = client.addOptions.includes('categoryId') ? await client.categories().catch(() => []) : [];\n return {\n downloaderId: handles.downloaderId(call.applet, key),\n label,\n canAdd: true,\n sourceKinds: options.fetchDocument ? ['bytes', 'url'] : ['bytes'],\n addOptions: [...new Set(client.addOptions)],\n categories: offered.map(({ name }) => ({\n categoryId: handles.categoryId(call.applet, key, name, true) as string,\n label: name,\n description: `The settings ${label} keeps for this category decide where files go and what is done with them afterwards`,\n })),\n actions: [...new Set(client.actions)],\n canReadFiles: false,\n ...NZB_LIMITS,\n };\n };\n return { downloaders: await Promise.all(nzbDownloaders(session).map(describe)) };\n}\n\n/**\n * `nzb.jobs`: one page of the jobs this applet submitted to one downloader, in\n * ascending byte order of their handles. Jobs the person or another applet added are\n * not listed; a downloader that cannot be asked is an error, not an empty page.\n *\n * @param session - The service's session.\n * @param call - Whose request this is.\n * @param raw - The `JobsRequest` as received.\n * @returns The `JobsResult`.\n * @example\n * ```ts\n * const { jobs, next } = await listNzbJobs(session, call, { downloaderId, limit: 10 });\n * ```\n */\nexport async function listNzbJobs(session: NzbSession, call: NzbCall, raw: unknown): Promise<NzbJobsResult> {\n const { downloaderId, after, limit } = readNzbJobs(raw);\n const downloader = nzbDownloaderOf(session, call.applet, downloaderId);\n const reported = new Map((await downloader.client.list()).map((job) => [job.id, job]));\n const jobs: NzbJob[] = [];\n for (const handle of session.handles.jobs(call.applet, downloader.key)) {\n const job = reported.get(handle.backend);\n if (job) jobs.push(describeNzbJob(session, { handle, downloader }, job));\n else session.handles.retire(call.applet, handle.id);\n }\n const visible = jobs.filter((job) => after === undefined || byteOrder(job.jobId) > byteOrder(after)).sort((left, right) => (byteOrder(left.jobId) < byteOrder(right.jobId) ? -1 : 1));\n const page = visible.slice(0, limit);\n return { jobs: page, next: visible.length > page.length ? (page.at(-1) as NzbJob).jobId : null };\n}\n\n/**\n * `nzb.status`: a fresh observation of one job the applet submitted.\n *\n * @param session - The service's session.\n * @param call - Whose request this is.\n * @param jobId - The job handle from the message.\n * @returns The `Job`.\n * @example\n * ```ts\n * (await nzbStatus(session, call, jobId)).state; // 'downloading'\n * ```\n */\nexport async function nzbStatus(session: NzbSession, call: NzbCall, jobId: unknown): Promise<NzbJob> {\n const owned = nzbJobOf(session, call.applet, jobId as string);\n return describeNzbJob(session, owned, await observeNzbJob(session, owned));\n}\n\n/**\n * `nzb.files` and `nzb.read`: always `unsupported`. kernl drives a downloader through\n * its own API and has no authorised mapping to what it saved; a path the downloader\n * reports is not one (NAP-NZB, Optional completed-file access).\n *\n * @param session - The service's session.\n * @param call - Whose request this is.\n * @param raw - The `FilesRequest` or `ReadRequest` as received.\n * @param reading - Whether this is `nzb.read`.\n * @returns Never; a job that is not the applet's is `not_found` first.\n * @example\n * ```ts\n * await nzbFiles(session, call, { jobId }, false); // rejects: unsupported\n * ```\n */\nexport async function nzbFiles(session: NzbSession, call: NzbCall, raw: unknown, reading: boolean): Promise<never> {\n need(!nzbJobOf(session, call.applet, readNzbFiles(raw, reading)).handle.gone, 'not_found', 'No such download');\n throw new NzbFault('unsupported', 'The shell cannot read what this downloader saved');\n}\n","import type { NappletMessage } from '@napplet/core';\nimport { createNamespacedStore } from '../persistence/store.js';\nimport { createNzbHandles } from './nzb-handles.js';\nimport { addNzb, controlNzb } from './nzb-mutations.js';\nimport { describeNzbDownloaders, listNzbJobs, nzbFiles, nzbStatus } from './nzb-queries.js';\nimport { createNzbReplay } from './nzb-replay.js';\nimport { readNzbEnvelope } from './nzb-requests.js';\nimport { nzbFaultOf, type NzbCall, type NzbServiceOptions, type NzbSession } from './nzb-session.js';\nimport { need, type NzbError } from './nzb-wire.js';\nimport type { DownloadService } from './types.js';\n\nexport { readNzbDocument, type NzbDocument } from './nzb-document.js';\nexport type { NzbDownloader, NzbServiceOptions } from './nzb-session.js';\n\n/** NAP-NZB, Shell Behavior: outstanding work is bounded; a window with this many requests waiting is told `rate_limited`. */\nconst MAX_WAITING = 16;\nconst REVOKED: NzbError = { code: 'permission_denied', message: 'This applet may no longer use downloads' };\n\ntype Answer = { readonly result: unknown } | { readonly error: NzbError };\ntype Reply = (answer: Answer) => void;\n\nconst OPERATIONS: Readonly<Record<string, (session: NzbSession, call: NzbCall, payload: unknown) => Promise<unknown>>> = {\n 'nzb.downloaders': describeNzbDownloaders,\n 'nzb.add': addNzb,\n 'nzb.jobs': listNzbJobs,\n 'nzb.status': nzbStatus,\n 'nzb.control': controlNzb,\n 'nzb.files': (session, call, payload) => nzbFiles(session, call, payload, false),\n 'nzb.read': (session, call, payload) => nzbFiles(session, call, payload, true),\n};\n\ntype Routable = NappletMessage & { readonly id: string };\n\n/** NAP-NZB, Wire Protocol: only a known type with a nonempty text `id` is answered; anything else is ignored. */\nconst routable = (message: NappletMessage & { readonly id?: unknown }): message is Routable => Object.hasOwn(OPERATIONS, message.type) && typeof message.id === 'string' && message.id !== '';\n\nfunction framed(message: Routable, body: Answer): NappletMessage {\n const result: Routable & Answer = { type: `${message.type}.result`, id: message.id, ...body };\n return result;\n}\n\n/**\n * The `nzb` service (NAP-NZB): applets hand NZB documents to the downloaders the\n * person already runs, and watch and steer the jobs they started.\n *\n * kernl is a remote control here. It never reads what a downloader saved, so `files`\n * and `read` are `unsupported` and every job says `canReadFiles: false`. The person is\n * asked before every add and before every delete. An applet sees only its own jobs,\n * under handles that mean nothing to anyone else. `add` and `control` are carried out\n * once per operation key, on a record that survives a reload. The runtime checks the\n * domain grant before a message gets here, so the handler does not check it again; it\n * declares every inbound type because `nzb` is not one of kehto's built-in domains.\n *\n * @param options - The downloaders, the optional fetcher, and the shell's applet, consent, storage and clock hooks.\n * @returns The handler to register as `nzb`, and `dispose`.\n * @example\n * ```ts\n * const nzb = createNzbService({ downloaders: () => [{ key: 'nzbget', label: 'Home', client }], appletOf, ownerOf, ask, storage: localStorage });\n * registry.nzb = nzb.handler;\n * ```\n */\nexport function createNzbService(options: NzbServiceOptions): DownloadService {\n const store = createNamespacedStore(options.storage, 'kernl');\n const clock = options.now ?? Date.now;\n const now = (): number => Math.floor(clock() / 1000);\n const lifetime = new AbortController();\n const turns = new Map<string, Promise<unknown>>();\n const waiting = new Map<string, Map<string, Reply>>();\n const session: NzbSession = {\n options,\n now,\n handles: createNzbHandles(store),\n replay: createNzbReplay(store, now),\n signal: lifetime.signal,\n inTurn(lane, work) {\n const run = (turns.get(lane) ?? Promise.resolve()).then(work);\n const settled = run.then(\n () => undefined,\n () => undefined,\n );\n turns.set(lane, settled);\n void settled.then(() => {\n if (turns.get(lane) === settled) turns.delete(lane);\n });\n return run;\n },\n };\n const answer = async (call: NzbCall, known: boolean, message: NappletMessage): Promise<Answer> => {\n need(known, 'permission_denied', 'Only a running applet may use downloads');\n const result = await (OPERATIONS[message.type] as (typeof OPERATIONS)[string])(session, call, readNzbEnvelope(message));\n // NAP-NZB, Shell Behavior: authorisation is checked again before anything is delivered.\n return call.live() ? { result } : { error: REVOKED };\n };\n return {\n handler: {\n descriptor: { name: 'nzb', version: '1.0.0', description: 'NZB downloads through the downloaders the person set up' },\n messageCapabilities: Object.fromEntries(Object.keys(OPERATIONS).map((type) => [type, null])),\n onPermissionDenied(_windowId, message, _reason, send) {\n if (routable(message)) send(framed(message, { error: { code: 'permission_denied', message: 'This applet may not use downloads' } }));\n },\n handleMessage(windowId, message, send) {\n if (!routable(message)) return;\n const { id } = message;\n const pending = waiting.get(windowId) ?? new Map<string, Reply>();\n if (pending.has(id)) return;\n const deliver = (body: Answer): void => send(framed(message, body));\n if (pending.size >= MAX_WAITING) {\n deliver({ error: { code: 'rate_limited', message: 'Too many requests are waiting; ask again when some have been answered' } });\n return;\n }\n const wanted = (): boolean => waiting.get(windowId)?.get(id) === reply;\n const reply: Reply = (body) => {\n if (!wanted()) return;\n pending.delete(id);\n deliver(body);\n };\n waiting.set(windowId, pending.set(id, reply));\n const applet = options.ownerOf(windowId);\n const call: NzbCall = { windowId, applet: applet ?? '', live: () => wanted() && options.ownerOf(windowId) === applet };\n void answer(call, applet !== undefined, message).then(reply, (error: unknown) => {\n const { code, message: words, replayUntil } = nzbFaultOf(error, false);\n reply({ error: { code, message: words, ...(replayUntil === undefined ? {} : { replayUntil }) } });\n });\n },\n onWindowDestroyed(windowId) {\n waiting.delete(windowId);\n },\n onPermissionRevoked(windowId) {\n for (const reply of waiting.get(windowId)?.values() ?? []) reply({ error: REVOKED });\n },\n },\n dispose() {\n lifetime.abort();\n waiting.clear();\n },\n };\n}\n","import type { SoulseekClient, SoulseekClientFile, SoulseekClientSearch } from '@kernlize/bridges';\nimport type { SoulseekErrorCode, SoulseekFailure, SoulseekFile, SoulseekQuery, SoulseekQueryKind, SoulseekQueryPage, SoulseekQueryReason, SoulseekQueryState, SoulseekTransferState } from '@napplet/core';\n\n/** The runtime limits `soulseek.info` reports; fixed for the service's life. */\nexport interface SoulseekLimits {\n readonly maxQueries: number;\n readonly maxTransfers: number;\n readonly maxResults: number;\n readonly maxPageSize: number;\n readonly maxReadBytes: number;\n readonly maxTextBytes: number;\n readonly queryTimeoutMs: number;\n readonly pollIntervalMs: number;\n}\n\n/** A NAP-SOULSEEK failure on its way to the `error` of a `.result` envelope. */\nexport class SoulseekFault extends Error {\n readonly code: SoulseekErrorCode;\n\n /**\n * @param code - The NAP-SOULSEEK error code.\n * @param message - Plain words for the applet; never an address, a credential or a path.\n * @example\n * ```ts\n * throw new SoulseekFault('not_found', 'Query handle is unavailable');\n * ```\n */\n constructor(code: SoulseekErrorCode, message: string) {\n super(message);\n this.code = code;\n }\n}\n\n/** Something whose operations run one after another. */\nexport interface SoulseekLane {\n tail: Promise<unknown>;\n}\n\n/**\n * The connection a query or transfer was admitted to. Its routing key is kept too, so work\n * started at one address is never carried on at the new address of the same connection.\n */\nexport interface SoulseekRoute {\n readonly id: string;\n readonly routingKey: string;\n}\n\n/** What a removed or locked connection's work fails with. */\nexport const SOULSEEK_GONE = 'That sharing program is no longer set up';\n\n/** What the daemon holds for one search, bound to the connection that started it. */\nexport interface SoulseekQueryDaemon {\n read(): Promise<SoulseekClientSearch>;\n /** Never rejects: stopping is best effort. */\n stop(): Promise<void>;\n /** Never rejects: stops, then deletes the search in the daemon. */\n forget(): Promise<void>;\n}\n\n/** One query a window holds. */\nexport interface SoulseekQueryRecord extends SoulseekLane {\n readonly id: string;\n readonly kind: SoulseekQueryKind;\n /** Where the query was made; its files are downloaded from there too. */\n readonly route: SoulseekRoute;\n /** Undefined for a browse, which is one answer and not a search the daemon keeps. */\n readonly daemon: SoulseekQueryDaemon | undefined;\n readonly files: SoulseekFile[];\n readonly keys: Set<string>;\n readonly deadline: number;\n state: SoulseekQueryState;\n ending: { reason?: SoulseekQueryReason; error?: SoulseekFailure };\n polledAt: number;\n released: boolean;\n}\n\n/** One transfer a window holds. */\nexport interface SoulseekTransferRecord extends SoulseekLane {\n readonly id: string;\n readonly file: SoulseekFile;\n /** The connection that admitted it; a transfer never moves to another one. */\n readonly route: SoulseekRoute;\n daemonId: string;\n /** Whether the daemon still holds an unfinished record kernl put there. */\n inDaemon: boolean;\n state: SoulseekTransferState;\n received: string;\n progress: { queuePosition?: number; bytesPerSecond?: number };\n ending: { error?: SoulseekFailure };\n polledAt: number;\n released: boolean;\n}\n\n/** Everything one window holds; nothing in it is reachable from another window. */\nexport interface SoulseekSession {\n closed: boolean;\n approved: boolean;\n asking: Promise<boolean> | undefined;\n readonly seen: Set<string>;\n readonly admissions: SoulseekLane;\n readonly queries: Map<string, SoulseekQueryRecord>;\n readonly files: Map<string, { readonly file: SoulseekFile; readonly query: SoulseekQueryRecord }>;\n readonly transfers: Map<string, SoulseekTransferRecord>;\n readonly byFile: Map<string, SoulseekTransferRecord>;\n}\n\n/** The window a request came from, and what that window holds. */\nexport interface SoulseekCall {\n readonly windowId: string;\n readonly session: SoulseekSession;\n}\n\n/** What the query and transfer halves of the service share. */\nexport interface SoulseekContext {\n readonly limits: SoulseekLimits;\n readonly now: () => number;\n /** Rejects `unavailable` unless this daemon is signed in to its network. */\n readonly online: (client: SoulseekClient) => Promise<void>;\n /**\n * A daemon once it is known to be signed in: the one `route` names, or the person's default\n * for new work. Rejects `unavailable` when it is not signed in or none is set up, and\n * `backend_error` when the named connection is gone.\n */\n readonly reach: (route?: SoulseekRoute) => Promise<{ readonly route: SoulseekRoute; readonly client: SoulseekClient }>;\n /** The live client of a route; undefined once the connection was removed, is locked or has a new address. */\n readonly clientOf: (route: SoulseekRoute) => SoulseekClient | undefined;\n /** Resolves once the person has said yes for this window; rejects `denied` on a no. */\n readonly consent: (windowId: string, session: SoulseekSession) => Promise<void>;\n}\n\nconst ENCODER = new TextEncoder();\nconst LONE_SURROGATE = /\\p{Surrogate}/u;\nconst BYTE_COUNT = /^(0|[1-9]\\d{0,19})$/;\nconst MAX_BYTE_COUNT = 18446744073709551615n;\nconst COLLECTION_FAILED = 'The sharing program stopped answering while results were gathered';\n\n/**\n * Swallows a rejection from work that is best effort, such as tidying up in the daemon.\n *\n * @returns Nothing.\n * @example\n * ```ts\n * await client.stopSearch(id).catch(ignore);\n * ```\n */\nexport function ignore(): undefined {\n return undefined;\n}\n\n/**\n * Runs work on a route's daemon, or rejects `backend_error` when that connection is gone.\n *\n * @param context - The service's shared parts.\n * @param route - The connection the work belongs to.\n * @param work - What to ask its daemon.\n * @returns What the work returns.\n * @example\n * ```ts\n * await onRoute(context, record.route, (client) => client.transfer(username, id));\n * ```\n */\nexport function onRoute<T>(context: SoulseekContext, route: SoulseekRoute, work: (client: SoulseekClient) => Promise<T>): Promise<T> {\n const client = context.clientOf(route);\n return client ? work(client) : Promise.reject(new SoulseekFault('backend_error', SOULSEEK_GONE));\n}\n\n/**\n * Issues a handle: opaque, never reused, and never one of the daemon's own ids.\n *\n * @param prefix - One letter naming what the handle is for.\n * @returns The handle, 38 bytes long.\n * @example\n * ```ts\n * issueSoulseekHandle('q'); // 'q-3f0c…'\n * ```\n */\nexport function issueSoulseekHandle(prefix: string): string {\n return `${prefix}-${crypto.randomUUID()}`;\n}\n\n/**\n * Runs work after everything already queued on a lane, whether that succeeded or not.\n *\n * @param lane - The session or record whose operations must not interleave.\n * @param work - What to run.\n * @returns What the work returns.\n * @example\n * ```ts\n * await serial(session.admissions, () => client.startSearch('rain', bounds));\n * ```\n */\nexport function serial<T>(lane: SoulseekLane, work: () => T | Promise<T>): Promise<T> {\n const run = lane.tail.then(work);\n lane.tail = run.catch(ignore);\n return run;\n}\n\n/**\n * Stops a pending request whose window ended (`revoked`) or whose object was released (`cancelled`).\n *\n * @param session - The window's session.\n * @param released - Whether the object the request works on was released meanwhile.\n * @returns Nothing when the request may go on.\n * @example\n * ```ts\n * alive(session, query.released);\n * ```\n */\nexport function alive(session: SoulseekSession, released = false): void {\n if (session.closed) throw new SoulseekFault('revoked', 'This window may no longer use the sharing program');\n if (released) throw new SoulseekFault('cancelled', 'This was released while the request was pending');\n}\n\n/**\n * Runs one operation on a query or transfer in its turn, and drops its result when the\n * object was released or the window ended while it ran.\n *\n * @param session - The window's session.\n * @param record - The query or transfer.\n * @param work - The operation.\n * @returns What the operation returns.\n * @example\n * ```ts\n * await within(session, transfer, () => refresh(transfer));\n * ```\n */\nexport function within<T>(session: SoulseekSession, record: SoulseekLane & { readonly released: boolean }, work: () => T | Promise<T>): Promise<T> {\n return serial(record, async () => {\n alive(session, record.released);\n const value = await work();\n alive(session, record.released);\n return value;\n });\n}\n\n/**\n * Admits new network work for a window: the daemon must be online and the person must\n * have said yes, and admissions for one window run one at a time so limits hold exactly.\n * The lane is taken only after the person answered (NAP-SOULSEEK, Transfer lifetime).\n *\n * @param context - The service's shared parts.\n * @param call - The window asking.\n * @param work - The admission, given the daemon it was admitted to and its route.\n * @param route - The connection the work must go to; the person's default when left out.\n * @returns What the admission returns.\n * @example\n * ```ts\n * await admitSoulseekWork(context, call, (client) => client.download(source), query.route);\n * ```\n */\nexport async function admitSoulseekWork<T>(context: SoulseekContext, call: SoulseekCall, work: (client: SoulseekClient, route: SoulseekRoute) => T | Promise<T>, route?: SoulseekRoute): Promise<T> {\n const reached = await context.reach(route);\n await context.consent(call.windowId, call.session);\n return serial(call.session.admissions, () => {\n alive(call.session);\n return work(reached.client, reached.route);\n });\n}\n\nfunction invalid(message: string): SoulseekFault {\n return new SoulseekFault('invalid_request', message);\n}\n\n/**\n * Rejects a request carrying a field its operation does not define.\n *\n * @param fields - The request's parameters.\n * @param names - The fields the operation defines.\n * @returns Nothing when every field is known.\n * @example\n * ```ts\n * onlyFields({ queryId: 'q-1', extra: 1 }, ['queryId']); // throws invalid_request\n * ```\n */\nexport function onlyFields(fields: object, names: readonly string[]): void {\n const unknown = Object.keys(fields).find((key) => !names.includes(key));\n if (unknown !== undefined) throw invalid('The request has a field this operation does not define');\n}\n\nfunction isText(value: unknown, maxBytes: number): value is string {\n return typeof value === 'string' && value !== '' && !value.includes('\\0') && !LONE_SURROGATE.test(value) && ENCODER.encode(value).length <= maxBytes;\n}\n\n/**\n * Reads a text parameter: nonempty, valid Unicode without U+0000, within the byte bound.\n *\n * @param value - What the applet sent.\n * @param name - The field's name, for the message.\n * @param maxBytes - `maxTextBytes`.\n * @returns The text.\n * @example\n * ```ts\n * textOf('q-1', 'queryId', 1024); // 'q-1'\n * ```\n */\nexport function textOf(value: unknown, name: string, maxBytes: number): string {\n if (!isText(value, maxBytes)) throw invalid(`${name} must be nonempty text of at most ${maxBytes} bytes, without U+0000`);\n return value;\n}\n\n/**\n * Reads an integer parameter within a range.\n *\n * @param value - What the applet sent.\n * @param name - The field's name, for the message.\n * @param range - The smallest and largest value allowed.\n * @returns The integer.\n * @example\n * ```ts\n * integerOf(25, 'limit', [1, 100]); // 25\n * ```\n */\nexport function integerOf(value: unknown, name: string, range: readonly [number, number]): number {\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < range[0] || value > range[1]) throw invalid(`${name} must be an integer from ${range[0]} to ${range[1]}`);\n return value;\n}\n\nfunction isByteCount(value: unknown): value is string {\n return typeof value === 'string' && BYTE_COUNT.test(value) && BigInt(value) <= MAX_BYTE_COUNT;\n}\n\n/**\n * Reads a byte count or offset: canonical unsigned decimal text up to 2^64 - 1.\n *\n * @param value - What the applet sent.\n * @param name - The field's name, for the message.\n * @returns The text, unchanged.\n * @example\n * ```ts\n * byteCountOf('00', 'offset'); // throws invalid_request\n * ```\n */\nexport function byteCountOf(value: unknown, name: string): string {\n if (!isByteCount(value)) throw invalid(`${name} is not canonical decimal text`);\n return value;\n}\n\nconst isCount = (value: unknown, least: number): value is number => typeof value === 'number' && Number.isSafeInteger(value) && value >= least;\n\n/**\n * Turns one entry a peer sent into what an applet may see, or nothing when the entry\n * cannot be represented. Optional hints a peer got wrong are dropped, not the entry.\n *\n * @param raw - The entry as the daemon reported it.\n * @param maxBytes - `maxTextBytes`; a name or path longer than this is not retained.\n * @returns The file without a handle, or undefined.\n * @example\n * ```ts\n * describeSoulseekFile({ username: 'ann', path: 'a\\\\b.flac', size: '3', locked: false }, 1024);\n * ```\n */\nexport function describeSoulseekFile(raw: SoulseekClientFile, maxBytes: number): Omit<SoulseekFile, 'fileId'> | undefined {\n if (!isText(raw.username, maxBytes) || !isText(raw.path, maxBytes) || !isByteCount(raw.size) || typeof raw.locked !== 'boolean') return undefined;\n return {\n username: raw.username,\n path: raw.path,\n size: raw.size,\n locked: raw.locked,\n ...(isText(raw.extension, maxBytes) ? { extension: raw.extension } : {}),\n ...(isCount(raw.bitrateKbps, 1) ? { bitrateKbps: raw.bitrateKbps } : {}),\n ...(isCount(raw.durationSeconds, 0) ? { durationSeconds: raw.durationSeconds } : {}),\n ...(isCount(raw.sampleRateHz, 1) ? { sampleRateHz: raw.sampleRateHz } : {}),\n ...(isCount(raw.bitDepth, 1) ? { bitDepth: raw.bitDepth } : {}),\n };\n}\n\nfunction browseFailure(error: Error): SoulseekFailure {\n if (error.message.startsWith('unavailable:peer-unavailable')) return { code: 'peer_unavailable', message: 'That person could not be reached' };\n if (error.message.startsWith('denied:peer')) return { code: 'peer_denied', message: 'That person does not share their list' };\n return { code: 'backend_error', message: 'The sharing program could not fetch the list' };\n}\n\n/** The query operations of the service, plus what teardown needs. */\nexport interface SoulseekQueries {\n search(call: SoulseekCall, fields: Record<string, unknown>): Promise<SoulseekQuery>;\n browse(call: SoulseekCall, fields: Record<string, unknown>): Promise<SoulseekQuery>;\n results(call: SoulseekCall, fields: Record<string, unknown>): Promise<SoulseekQueryPage>;\n stop(call: SoulseekCall, fields: Record<string, unknown>): Promise<SoulseekQuery>;\n /** Resolves false when the window holds no such query. */\n release(session: SoulseekSession, handle: string): Promise<boolean>;\n /** Removes the query and its file handles now, then stops and deletes it in the daemon. */\n discard(session: SoulseekSession, query: SoulseekQueryRecord): Promise<void>;\n}\n\nfunction snapshotOf(limits: SoulseekLimits, query: SoulseekQueryRecord): SoulseekQuery {\n return {\n queryId: query.id,\n kind: query.kind,\n state: query.state,\n count: query.files.length,\n maxResults: limits.maxResults,\n maxPageSize: limits.maxPageSize,\n timeoutMs: limits.queryTimeoutMs,\n ...query.ending,\n };\n}\n\nfunction finish(query: SoulseekQueryRecord, state: SoulseekQueryState, ending: SoulseekQueryRecord['ending']): void {\n query.state = state;\n query.ending = ending;\n}\n\n/** A browse has one answer to wait for; past its deadline it has failed, whenever that is noticed. */\nfunction expire(context: SoulseekContext, query: SoulseekQueryRecord): void {\n if (query.state === 'collecting' && !query.daemon && context.now() >= query.deadline) finish(query, 'failed', { error: { code: 'timeout', message: 'That person did not send their list in time' } });\n}\n\nfunction retain(context: SoulseekContext, session: SoulseekSession, query: SoulseekQueryRecord, incoming: readonly SoulseekClientFile[]): { lost: boolean; overflow: boolean } {\n const { maxResults, maxTextBytes } = context.limits;\n let lost = false;\n for (const raw of incoming) {\n const file = describeSoulseekFile(raw, maxTextBytes);\n const key = JSON.stringify([raw.username, raw.path, raw.size]);\n if (!file) lost = true;\n else if (!query.keys.has(key)) {\n if (query.files.length >= maxResults) return { lost, overflow: true };\n const entry = { fileId: issueSoulseekHandle('f'), ...file };\n query.keys.add(key);\n query.files.push(entry);\n session.files.set(entry.fileId, { file: entry, query });\n }\n }\n return { lost, overflow: false };\n}\n\n/** Reads what a search has found since the last look, when a look is due, and ends the search when its rules say so. */\nasync function gather(context: SoulseekContext, session: SoulseekSession, query: SoulseekQueryRecord): Promise<void> {\n const { limits } = context;\n expire(context, query);\n const { daemon } = query;\n const now = context.now();\n const due = now >= query.deadline;\n if (query.state !== 'collecting' || !daemon || (!due && now - query.polledAt < limits.pollIntervalMs)) return;\n query.polledAt = now;\n if (!context.clientOf(query.route)) return finish(query, 'failed', { error: { code: 'backend_error', message: SOULSEEK_GONE } });\n const found = await daemon.read().catch(ignore);\n if (query.state !== 'collecting') return;\n if (!found) return finish(query, 'failed', { error: { code: 'backend_error', message: COLLECTION_FAILED } });\n retain(context, session, query, found.files);\n if (query.files.length >= limits.maxResults) finish(query, 'complete', { reason: 'limit' });\n else if (found.complete || due) finish(query, 'complete', { reason: 'deadline' });\n else return;\n if (!found.complete) await daemon.stop();\n}\n\nfunction settle(context: SoulseekContext, session: SoulseekSession, query: SoulseekQueryRecord, listing: readonly SoulseekClientFile[]): void {\n const { lost, overflow } = retain(context, session, query, listing);\n if (lost) finish(query, 'failed', { error: { code: 'backend_error', message: 'Part of the list could not be read' } });\n else finish(query, 'complete', { reason: overflow ? 'limit' : 'peer_complete' });\n}\n\nfunction discard(session: SoulseekSession, query: SoulseekQueryRecord): Promise<void> {\n session.queries.delete(query.id);\n for (const file of query.files) session.files.delete(file.fileId);\n query.released = true;\n // A terminal state is what makes a late answer from the daemon or a peer get discarded.\n if (query.state === 'collecting') finish(query, 'stopped', { reason: 'cancelled' });\n return serial(query, async () => {\n await query.daemon?.forget();\n });\n}\n\n/**\n * The query half of the `soulseek` service: searches and browses, gathered lazily as\n * the applet polls, each bound to the window that started it.\n *\n * @param context - Limits, clock, the daemon and the person's consent.\n * @returns The `search`, `browse`, `results` and `stop` operations, and release.\n * @example\n * ```ts\n * const queries = createSoulseekQueries(context);\n * const query = await queries.search(call, { request: { text: 'field recording' } });\n * ```\n */\nexport function createSoulseekQueries(context: SoulseekContext): SoulseekQueries {\n const { limits } = context;\n const snapshot = (query: SoulseekQueryRecord): SoulseekQuery => snapshotOf(limits, query);\n const room = (session: SoulseekSession): void => {\n if (session.queries.size >= limits.maxQueries) throw new SoulseekFault('limit_exceeded', `This window already holds ${limits.maxQueries} searches; release one first`);\n };\n const open = (session: SoulseekSession, kind: SoulseekQueryKind, route: SoulseekRoute, daemon: SoulseekQueryDaemon | undefined): SoulseekQueryRecord => {\n const query: SoulseekQueryRecord = { id: issueSoulseekHandle('q'), kind, route, daemon, files: [], keys: new Set(), deadline: context.now() + limits.queryTimeoutMs, state: 'collecting', ending: {}, polledAt: context.now(), released: false, tail: Promise.resolve() };\n session.queries.set(query.id, query);\n return query;\n };\n const owned = (session: SoulseekSession, fields: Record<string, unknown>): SoulseekQueryRecord => {\n const query = session.queries.get(textOf(fields.queryId, 'queryId', limits.maxTextBytes));\n if (!query) throw new SoulseekFault('not_found', 'Query handle is unavailable');\n return query;\n };\n return {\n async search(call, fields) {\n onlyFields(fields, ['request']);\n const { request } = fields;\n if (typeof request !== 'object' || request === null) throw invalid('request must be a record');\n onlyFields(request, ['text', 'username']);\n const { text, username } = request as { text?: unknown; username?: unknown };\n if (textOf(text, 'text', limits.maxTextBytes).trim() === '') throw invalid('text must have a character that is not white space');\n const peer = username === undefined ? {} : { username: textOf(username, 'username', limits.maxTextBytes) };\n return admitSoulseekWork(context, call, async (client, route) => {\n const { session } = call;\n room(session);\n const { id } = await client.startSearch(text as string, { ...peer, timeoutMs: limits.queryTimeoutMs, limit: limits.maxResults });\n // Every later look goes to the connection by its route, so one removed meanwhile is never asked.\n const stop = (): Promise<void> => onRoute(context, route, (daemon) => daemon.stopSearch(id)).catch(ignore);\n const daemon: SoulseekQueryDaemon = {\n read: () => onRoute(context, route, (daemon) => daemon.searchResults(id)),\n stop,\n forget: () => stop().then(() => onRoute(context, route, (daemon) => daemon.deleteSearch(id))).catch(ignore),\n };\n if (session.closed) await daemon.forget();\n alive(session);\n return snapshot(open(session, 'search', route, daemon));\n });\n },\n async browse(call, fields) {\n onlyFields(fields, ['username']);\n const username = textOf(fields.username, 'username', limits.maxTextBytes);\n return admitSoulseekWork(context, call, (client, route) => {\n const { session } = call;\n room(session);\n const query = open(session, 'browse', route, undefined);\n const land = (apply: () => void): void => {\n expire(context, query);\n if (query.state === 'collecting') apply();\n };\n void client.browse(username).then(\n (listing) => land(() => settle(context, session, query, listing)),\n (error: Error) => land(() => finish(query, 'failed', { error: browseFailure(error) })),\n );\n return snapshot(query);\n });\n },\n async results({ session }, fields) {\n onlyFields(fields, ['queryId', 'after', 'limit']);\n const after = fields.after === undefined ? 0 : integerOf(fields.after, 'after', [0, Number.MAX_SAFE_INTEGER]);\n const limit = fields.limit === undefined ? limits.maxPageSize : integerOf(fields.limit, 'limit', [1, limits.maxPageSize]);\n const query = owned(session, fields);\n return within(session, query, async () => {\n await gather(context, session, query);\n if (after > query.files.length) throw invalid('after is past the last result');\n const files = query.files.slice(after, after + limit);\n return { query: snapshot(query), files, next: after + files.length };\n });\n },\n async stop({ session }, fields) {\n onlyFields(fields, ['queryId']);\n const query = owned(session, fields);\n return within(session, query, async () => {\n await gather(context, session, query);\n if (query.state === 'collecting') {\n finish(query, 'stopped', { reason: 'cancelled' });\n await query.daemon?.stop();\n }\n return snapshot(query);\n });\n },\n async release(session, handle) {\n const query = session.queries.get(handle);\n if (query) await discard(session, query);\n return query !== undefined;\n },\n discard,\n };\n}\n","import type { SoulseekClientFailure, SoulseekClientTransfer } from '@kernlize/bridges';\nimport type { SoulseekErrorCode, SoulseekSaved, SoulseekTransfer, SoulseekTransferState } from '@napplet/core';\nimport {\n SoulseekFault,\n admitSoulseekWork,\n alive,\n byteCountOf,\n ignore,\n integerOf,\n issueSoulseekHandle,\n onRoute,\n onlyFields,\n SOULSEEK_GONE,\n serial,\n textOf,\n within,\n type SoulseekCall,\n type SoulseekContext,\n type SoulseekSession,\n type SoulseekTransferRecord,\n} from './soulseek-queries.js';\n\nconst TERMINAL: ReadonlySet<SoulseekTransferState> = new Set(['complete', 'cancelled', 'failed']);\nconst ACTIVE: ReadonlySet<SoulseekTransferState> = new Set(['queued', 'transferring']);\nconst UNREACHABLE = 'The sharing program could not be reached';\nconst FAILURE_WORDS: Record<SoulseekClientFailure, string> = {\n peer_unavailable: 'That person could not be reached',\n peer_denied: 'That person refused to send the file',\n timeout: 'The download took too long to start',\n limit_exceeded: 'The sharing program had no room for the download',\n backend_error: 'The sharing program could not finish the download',\n};\n\n/** The transfer operations of the service, plus what teardown needs. */\nexport interface SoulseekTransfers {\n download(call: SoulseekCall, fields: Record<string, unknown>): Promise<SoulseekTransfer>;\n transfers(call: SoulseekCall, fields: Record<string, unknown>): Promise<SoulseekTransfer[]>;\n status(call: SoulseekCall, fields: Record<string, unknown>): Promise<SoulseekTransfer>;\n pause(call: SoulseekCall, fields: Record<string, unknown>): Promise<SoulseekTransfer>;\n resume(call: SoulseekCall, fields: Record<string, unknown>): Promise<SoulseekTransfer>;\n cancel(call: SoulseekCall, fields: Record<string, unknown>): Promise<SoulseekTransfer>;\n read(call: SoulseekCall, fields: Record<string, unknown>): Promise<never>;\n save(call: SoulseekCall, fields: Record<string, unknown>): Promise<SoulseekSaved>;\n /** Resolves false when the window holds no such transfer. */\n release(session: SoulseekSession, handle: string): Promise<boolean>;\n /** Removes the transfer now, then cancels and removes it in the daemon unless it finished. */\n discard(session: SoulseekSession, record: SoulseekTransferRecord): Promise<void>;\n}\n\nfunction fail(record: SoulseekTransferRecord, code: SoulseekErrorCode, message: string): void {\n record.state = 'failed';\n record.progress = {};\n record.ending = { error: { code, message } };\n}\n\nfunction finished(record: SoulseekTransferRecord): void {\n if (record.state !== 'complete') throw new SoulseekFault('invalid_state', 'The download has not finished');\n}\n\nfunction retryable(record: SoulseekTransferRecord): void {\n if (TERMINAL.has(record.state)) throw new SoulseekFault('invalid_state', 'The download has ended; release it and ask for the file again');\n}\n\n/** Plain words for a failed call to the daemon: that its connection is gone, or that it could not be reached. */\nconst wordsOf = (error: unknown): string => (error instanceof SoulseekFault ? error.message : UNREACHABLE);\n\n/** Resolves false, with the transfer failed, when the daemon did not confirm the stop. */\nfunction halt(context: SoulseekContext, record: SoulseekTransferRecord, remove: boolean): Promise<boolean> {\n return onRoute(context, record.route, (client) => client.cancel(record.file.username, record.daemonId, remove)).then(\n () => true,\n (error: unknown) => {\n fail(record, 'backend_error', wordsOf(error));\n return false;\n },\n );\n}\n\n/** Cancels and removes what kernl put in the daemon for a transfer, unless it finished, is already gone, or its connection is. */\nasync function drop(context: SoulseekContext, record: SoulseekTransferRecord): Promise<void> {\n if (!record.inDaemon) return;\n await onRoute(context, record.route, (client) => client.cancel(record.file.username, record.daemonId, true)).then(() => {\n record.inDaemon = false;\n }, ignore);\n}\n\nfunction observe(record: SoulseekTransferRecord, seen: SoulseekClientTransfer): void {\n const size = BigInt(record.file.size);\n const got = BigInt(seen.received);\n record.received = got > size ? record.file.size : seen.received;\n if (seen.state === 'failed') return fail(record, seen.failure ?? 'backend_error', FAILURE_WORDS[seen.failure ?? 'backend_error']);\n if (seen.state === 'complete' && got !== size) return fail(record, 'backend_error', 'The sharing program ended the download without the whole file');\n record.state = seen.state;\n record.progress = {};\n // A finished file belongs to the person: nothing kernl does later may touch it in the daemon.\n if (seen.state === 'complete') record.inDaemon = false;\n if (seen.state === 'cancelled') record.received = '0';\n if (seen.state === 'queued' && seen.queuePosition !== undefined && seen.queuePosition > 0) record.progress = { queuePosition: seen.queuePosition };\n if (seen.state === 'transferring' && seen.bytesPerSecond !== undefined) record.progress = { bytesPerSecond: seen.bytesPerSecond };\n}\n\n/** Reads a running transfer's progress from the daemon, when a look is due. */\nasync function refresh(context: SoulseekContext, record: SoulseekTransferRecord): Promise<void> {\n const now = context.now();\n if (!ACTIVE.has(record.state) || now - record.polledAt < context.limits.pollIntervalMs) return;\n record.polledAt = now;\n const answer = await onRoute(context, record.route, (client) => client.transfer(record.file.username, record.daemonId)).then(\n (seen) => ({ seen }),\n (error: unknown) => ({ lost: wordsOf(error) }),\n );\n if ('lost' in answer) return fail(record, 'backend_error', answer.lost);\n if (!answer.seen) {\n record.inDaemon = false;\n return fail(record, 'backend_error', 'The sharing program no longer has this download');\n }\n if (answer.seen.size !== record.file.size) {\n fail(record, 'source_changed', 'The file is not the size it was listed with');\n return drop(context, record);\n }\n observe(record, answer.seen);\n}\n\n/** The daemon cannot pause, so a resume asks it for the same file again and forgets the stopped attempt. */\nasync function requeue(context: SoulseekContext, record: SoulseekTransferRecord): Promise<void> {\n const client = context.clientOf(record.route);\n if (!client) return fail(record, 'backend_error', SOULSEEK_GONE);\n await context.online(client);\n const { username, path, size } = record.file;\n const previous = record.daemonId;\n const next = await client.download({ username, path, size }).catch(ignore);\n if (!next) return fail(record, 'backend_error', UNREACHABLE);\n record.daemonId = next.id;\n record.state = 'queued';\n record.polledAt = context.now();\n if (next.id !== previous) await client.cancel(username, previous, true).catch(ignore);\n}\n\nfunction discard(context: SoulseekContext, session: SoulseekSession, record: SoulseekTransferRecord): Promise<void> {\n session.transfers.delete(record.id);\n session.byFile.delete(record.file.fileId);\n record.released = true;\n return serial(record, () => drop(context, record));\n}\n\n/**\n * The transfer half of the `soulseek` service: downloads the person's daemon carries\n * out, each bound to the file handle it was asked for and the window that asked.\n *\n * The daemon is somewhere kernl cannot read files from, so `read` is `denied` and\n * `save` is `unsupported`; a finished file stays in the daemon. The daemon cannot\n * pause, so a pause cancels there and a resume asks for the same file again.\n *\n * @param context - Limits, clock, the daemon and the person's consent.\n * @returns The transfer operations, and release.\n * @example\n * ```ts\n * const transfers = createSoulseekTransfers(context);\n * const transfer = await transfers.download(call, { fileId });\n * ```\n */\nexport function createSoulseekTransfers(context: SoulseekContext): SoulseekTransfers {\n const { limits } = context;\n const snapshot = (record: SoulseekTransferRecord): SoulseekTransfer => ({\n transferId: record.id,\n file: record.file,\n state: record.state,\n maxReadBytes: limits.maxReadBytes,\n received: record.received,\n ...record.progress,\n ...record.ending,\n });\n const find = (session: SoulseekSession, fields: Record<string, unknown>): SoulseekTransferRecord => {\n const record = session.transfers.get(textOf(fields.transferId, 'transferId', limits.maxTextBytes));\n if (!record) throw new SoulseekFault('not_found', 'Transfer handle is unavailable');\n return record;\n };\n const owned = (session: SoulseekSession, fields: Record<string, unknown>): SoulseekTransferRecord => {\n onlyFields(fields, ['transferId']);\n return find(session, fields);\n };\n return {\n async download(call, fields) {\n const { session } = call;\n onlyFields(fields, ['fileId']);\n const fileId = textOf(fields.fileId, 'fileId', limits.maxTextBytes);\n const entry = session.files.get(fileId);\n if (!entry) throw new SoulseekFault('not_found', 'File handle is unavailable');\n const existing = session.byFile.get(fileId);\n if (existing) return snapshot(existing);\n // A file is downloaded from the connection its query was made on, never the person's current default.\n return admitSoulseekWork(context, call, async (client, route) => {\n alive(session, session.files.get(fileId) !== entry);\n const admitted = session.byFile.get(fileId);\n if (admitted) return snapshot(admitted);\n if (session.transfers.size >= limits.maxTransfers) throw new SoulseekFault('limit_exceeded', `This window already holds ${limits.maxTransfers} downloads; release one first`);\n const { username, path, size } = entry.file;\n const { id } = await client.download({ username, path, size });\n if (session.closed || session.files.get(fileId) !== entry) {\n await client.cancel(username, id, true).catch(ignore);\n alive(session, true);\n }\n const record: SoulseekTransferRecord = { id: issueSoulseekHandle('t'), file: entry.file, route, daemonId: id, inDaemon: true, state: 'queued', received: '0', progress: {}, ending: {}, polledAt: context.now(), released: false, tail: Promise.resolve() };\n session.transfers.set(record.id, record);\n session.byFile.set(fileId, record);\n return snapshot(record);\n }, entry.query.route);\n },\n async transfers({ session }, fields) {\n onlyFields(fields, []);\n await Promise.all([...session.transfers.values()].map((record) => serial(record, () => refresh(context, record))));\n alive(session);\n return [...session.transfers.values()].map(snapshot);\n },\n async status({ session }, fields) {\n const record = owned(session, fields);\n return within(session, record, async () => {\n await refresh(context, record);\n return snapshot(record);\n });\n },\n async pause({ session }, fields) {\n const record = owned(session, fields);\n return within(session, record, async () => {\n retryable(record);\n if (record.state !== 'paused' && (await halt(context, record, false))) {\n record.state = 'paused';\n record.progress = {};\n }\n return snapshot(record);\n });\n },\n async resume({ session }, fields) {\n const record = owned(session, fields);\n return within(session, record, async () => {\n retryable(record);\n if (record.state === 'paused') await requeue(context, record);\n return snapshot(record);\n });\n },\n async cancel({ session }, fields) {\n const record = owned(session, fields);\n return within(session, record, async () => {\n if (!TERMINAL.has(record.state) && (await halt(context, record, true))) {\n record.state = 'cancelled';\n record.received = '0';\n record.progress = {};\n record.inDaemon = false;\n }\n return snapshot(record);\n });\n },\n async read({ session }, fields) {\n onlyFields(fields, ['transferId', 'offset', 'length']);\n const offset = byteCountOf(fields.offset, 'offset');\n integerOf(fields.length, 'length', [1, limits.maxReadBytes]);\n const record = find(session, fields);\n if (BigInt(offset) > BigInt(record.file.size)) throw new SoulseekFault('invalid_request', 'offset is past the end of the file');\n finished(record);\n throw new SoulseekFault('denied', 'kernl cannot read what the sharing program downloaded; the file is in that program');\n },\n async save({ session }, fields) {\n finished(owned(session, fields));\n throw new SoulseekFault('unsupported', 'kernl cannot save what the sharing program downloaded; the file is in that program');\n },\n async release(session, handle) {\n const record = session.transfers.get(handle);\n if (record) await discard(context, session, record);\n return record !== undefined;\n },\n discard: (session, record) => discard(context, session, record),\n };\n}\n","import type { ServiceHandler } from '@kehto/runtime';\nimport type { SoulseekClient } from '@kernlize/bridges';\nimport type { ConnectionRouting } from './connections.js';\nimport type { NappletMessage, SoulseekFailure, SoulseekInfo, SoulseekReleased } from '@napplet/core';\nimport {\n SOULSEEK_GONE,\n SoulseekFault,\n alive,\n createSoulseekQueries,\n onlyFields,\n textOf,\n type SoulseekCall,\n type SoulseekContext,\n type SoulseekLimits,\n type SoulseekRoute,\n type SoulseekSession,\n} from './soulseek-queries.js';\nimport { createSoulseekTransfers } from './soulseek-transfers.js';\nimport type { DownloadQuestion, DownloadService, DownloadServiceDeps } from './types.js';\n\nexport type { SoulseekLimits } from './soulseek-queries.js';\n\n/** What the `soulseek` service needs from the shell. */\nexport interface SoulseekServiceOptions extends DownloadServiceDeps {\n /** The person's Soulseek connections, read on every request: new searches go to the default, and what they find stays on it. */\n readonly connections: ConnectionRouting<SoulseekClient>;\n /** Runtime limits; each has the default in {@link DEFAULT_SOULSEEK_LIMITS}. */\n readonly limits?: Partial<SoulseekLimits>;\n}\n\n/**\n * The limits a window works within unless the host says otherwise.\n *\n * @example\n * ```ts\n * createSoulseekService({ ...deps, connections: programs.routing('soulseek'), limits: { ...DEFAULT_SOULSEEK_LIMITS, maxTransfers: 4 } });\n * ```\n */\nexport const DEFAULT_SOULSEEK_LIMITS: SoulseekLimits = {\n maxQueries: 4,\n maxTransfers: 16,\n maxResults: 500,\n maxPageSize: 100,\n maxReadBytes: 65536,\n maxTextBytes: 1024,\n queryTimeoutMs: 30000,\n pollIntervalMs: 1000,\n};\n\n/**\n * What the person is asked before a window first reaches the network through their\n * daemon: who learns what, that nothing is private on the way, and when it ends.\n *\n * @example\n * ```ts\n * SOULSEEK_SESSION_QUESTION.title; // 'Search, browse and fetch through your sharing program'\n * ```\n */\nexport const SOULSEEK_SESSION_QUESTION: DownloadQuestion = {\n kind: 'session',\n title: 'Search, browse and fetch through your sharing program',\n lines: [\n { label: 'Who sees it', value: \"The network's server and the people whose files are involved see your search words, the names of the files you ask for, and the network address of the machine running the program\" },\n { label: 'Privacy', value: 'Nothing is encrypted end to end' },\n { label: 'Until', value: \"Downloads stop when this applet's window closes\" },\n ],\n};\n\ntype Operation = (call: SoulseekCall, fields: Record<string, unknown>) => Promise<unknown>;\n\n/** Marks a repeated request id, which is neither run again nor answered (NAP-SOULSEEK, Wire Protocol). */\nconst REPEATED = Symbol('repeated');\n\nfunction failureOf(error: unknown): SoulseekFailure {\n if (error instanceof SoulseekFault) return { code: error.code, message: error.message };\n return { code: 'backend_error', message: 'The sharing program did not do what was asked' };\n}\n\n/**\n * The `soulseek` service: an applet searches, browses and downloads through the\n * Soulseek daemon the person already runs (NAP-SOULSEEK).\n *\n * Every handle belongs to the window it was issued to; another window, even of the\n * same applet, cannot tell one from a handle that never existed. The person is asked\n * once per window before it first reaches the network. Nothing outlives the window:\n * closing it, or taking its grant back, stops its searches and unfinished downloads\n * in the daemon and leaves finished files there, untouched.\n *\n * The daemon is a separate program whose files kernl cannot reach, so `read` is\n * `denied`, `save` is `unsupported` and `info` reports `canSave: false`. The runtime\n * checks the domain grant before a message gets here; this handler does not repeat it.\n *\n * @param options - The daemon, the person's consent, the clock and the limits.\n * @returns The handler to register as `soulseek`, and `dispose`.\n * @example\n * ```ts\n * const soulseek = createSoulseekService({ connections: programs.routing('soulseek'), appletOf, ownerOf, ask, storage });\n * registry.soulseek = soulseek.handler;\n * ```\n */\nexport function createSoulseekService(options: SoulseekServiceOptions): DownloadService {\n const limits: SoulseekLimits = { ...DEFAULT_SOULSEEK_LIMITS, ...options.limits };\n const sessions = new Map<string, SoulseekSession>();\n const stateOf = (client: SoulseekClient): Promise<'offline' | 'online'> => client.state().catch(() => 'offline');\n /** A route's client only while the connection is there, serving, and at the address the route was made at. */\n const clientOf = (route: SoulseekRoute): SoulseekClient | undefined => {\n const routed = options.connections.byId(route.id);\n return routed?.connection.routingKey === route.routingKey ? routed.client : undefined;\n };\n const preferred = (): { readonly route: SoulseekRoute; readonly client: SoulseekClient | undefined } => {\n const routed = options.connections.preferred();\n return { route: { id: routed?.connection.id ?? '', routingKey: routed?.connection.routingKey ?? '' }, client: routed?.client };\n };\n const context: SoulseekContext = {\n limits,\n now: options.now ?? Date.now,\n async online(client) {\n if ((await stateOf(client)) !== 'online') throw new SoulseekFault('unavailable', 'The sharing program is not connected to its network');\n },\n clientOf,\n async reach(named) {\n const reached = named ? { route: named, client: clientOf(named) } : preferred();\n if (!reached.client) throw named ? new SoulseekFault('backend_error', SOULSEEK_GONE) : new SoulseekFault('unavailable', 'No sharing program is set up');\n await context.online(reached.client);\n return { route: reached.route, client: reached.client };\n },\n async consent(windowId, session) {\n if (session.approved) return;\n const asking = (session.asking ??= options.ask(windowId, SOULSEEK_SESSION_QUESTION).then(\n (yes) => yes,\n () => false,\n ));\n const yes = await asking;\n if (session.asking === asking) session.asking = undefined;\n alive(session);\n if (!yes) throw new SoulseekFault('denied', 'The person said no');\n session.approved = true;\n },\n };\n const queries = createSoulseekQueries(context);\n const transfers = createSoulseekTransfers(context);\n const operations = new Map<string, Operation>(\n Object.entries<Operation>({\n async info(_call, fields): Promise<SoulseekInfo> {\n onlyFields(fields, []);\n const client = options.connections.preferred()?.client;\n return { state: client ? await stateOf(client) : 'unconfigured', canSave: false, ...limits };\n },\n async release({ session }, fields): Promise<SoulseekReleased> {\n onlyFields(fields, ['kind', 'handle']);\n const handle = textOf(fields.handle, 'handle', limits.maxTextBytes);\n if (fields.kind !== 'query' && fields.kind !== 'transfer') throw new SoulseekFault('invalid_request', 'kind must be \"query\" or \"transfer\"');\n return { released: await (fields.kind === 'query' ? queries : transfers).release(session, handle) };\n },\n search: queries.search,\n browse: queries.browse,\n results: queries.results,\n stop: queries.stop,\n download: transfers.download,\n transfers: transfers.transfers,\n status: transfers.status,\n pause: transfers.pause,\n resume: transfers.resume,\n cancel: transfers.cancel,\n read: transfers.read,\n save: transfers.save,\n }).map(([name, run]) => [`soulseek.${name}`, run]),\n );\n const sessionOf = (windowId: string): SoulseekSession => {\n let session = sessions.get(windowId);\n if (!session) {\n session = { closed: false, approved: false, asking: undefined, seen: new Set(), admissions: { tail: Promise.resolve() }, queries: new Map(), files: new Map(), transfers: new Map(), byFile: new Map() };\n sessions.set(windowId, session);\n }\n return session;\n };\n const accept = async (windowId: string, id: string, run: Operation, fields: Record<string, unknown>): Promise<unknown> => {\n if (!options.appletOf(windowId)) throw new SoulseekFault('denied', 'This window is not a running applet');\n textOf(id, 'id', limits.maxTextBytes);\n const session = sessionOf(windowId);\n if (session.seen.has(id)) return REPEATED;\n session.seen.add(id);\n return run({ windowId, session }, fields);\n };\n const end = (windowId: string): void => {\n const session = sessions.get(windowId);\n if (!session) return;\n sessions.delete(windowId);\n session.closed = true;\n for (const query of session.queries.values()) void queries.discard(session, query);\n for (const record of session.transfers.values()) void transfers.discard(session, record);\n };\n const dispose = (): void => {\n for (const windowId of sessions.keys()) end(windowId);\n };\n const handler: ServiceHandler = {\n descriptor: { name: 'soulseek', version: '1.0.0', description: \"Searches and downloads through the person's own sharing program\" },\n messageCapabilities: Object.fromEntries([...operations.keys()].map((type) => [type, null])),\n handleMessage(windowId, message, send) {\n const { type, id, ...fields } = message as { type: string; id?: unknown } & Record<string, unknown>;\n const run = operations.get(type);\n if (!run || typeof id !== 'string' || id === '') return;\n const reply = (body: { value: unknown } | { error: SoulseekFailure }): void => {\n const result: NappletMessage & Record<string, unknown> = { type: `${type}.result`, id, ...body };\n send(result);\n };\n void accept(windowId, id, run, fields).then(\n (value) => {\n if (value !== REPEATED) reply({ value });\n },\n (error: unknown) => reply({ error: failureOf(error) }),\n );\n },\n onWindowDestroyed: end,\n onPermissionRevoked: end,\n onUnregistered: dispose,\n };\n return { handler, dispose };\n}\n","import { magnetInfoHash, readTorrentMetainfo, type TorrentClientSource } from '@kernlize/bridges';\nimport type { TorrentCapabilities, TorrentRetention } from '@napplet/core';\n\n/** The two ways kernl can run a torrent in a program it only controls from outside. */\nexport type TorrentServiceMode = 'download' | 'download-and-seed';\n\n/**\n * Every request an applet can send, with the name its answer travels under. `ack` and\n * `result` answers are records that say `ok: false` themselves; the others answer a\n * failure with a top-level `error`.\n */\nexport const TORRENT_REQUESTS: Readonly<Record<string, 'ack' | 'capabilities' | 'files' | 'jobs' | 'result' | 'status'>> = {\n 'torrent.capabilities': 'capabilities',\n 'torrent.pickFiles': 'result',\n 'torrent.add': 'ack',\n 'torrent.status': 'status',\n 'torrent.jobs': 'jobs',\n 'torrent.files': 'files',\n 'torrent.selectFiles': 'status',\n 'torrent.pause': 'status',\n 'torrent.resume': 'status',\n 'torrent.remove': 'result',\n 'torrent.metadata': 'result',\n 'torrent.read': 'result',\n 'torrent.exportMetainfo': 'result',\n 'torrent.saveFile': 'result',\n 'torrent.openFile': 'result',\n 'torrent.cancel': 'result',\n 'torrent.update': 'result',\n};\n\n/** What the service sends a window without being asked. */\nexport const TORRENT_PUSHES: readonly string[] = ['torrent.state', 'torrent.progress', 'torrent.error'];\n\nconst MEBIBYTE = 1024 * 1024;\nconst MAX_MAGNET_LENGTH = 16 * 1024;\nconst MAX_TITLE_LENGTH = 200;\nconst V1_ONLY = 'Only BitTorrent v1 torrents can be handed on.';\nconst UNREACHABLE = 'Your torrent program could not be reached.';\nconst MODES: readonly string[] = ['download', 'seed', 'download-and-seed'];\nconst STATES: readonly string[] = ['queued', 'metadata', 'downloading', 'seeding', 'paused', 'complete', 'cancelled', 'error'];\n\n/**\n * What kernl offers over a torrent program it reaches through that program's own API.\n * It cannot read the program's files, so reads, saving, opening, exporting and seeding\n * local files are all off; the read limits are the smallest the schema allows.\n */\nexport const TORRENT_CAPABILITIES: TorrentCapabilities = {\n transports: ['bittorrent'],\n modes: ['download', 'download-and-seed'],\n formats: ['v1'],\n createFormats: [],\n retentions: ['session', 'persistent'],\n mutableSettings: ['downloadLimitBytesPerSecond', 'uploadLimitBytesPerSecond', 'seedAfterComplete'],\n maxReadBytes: 1,\n maxReadWaitMs: 1,\n maxPendingReads: 1,\n maxMetainfoBytes: 2 * MEBIBYTE,\n canSaveFiles: false,\n canOpenFiles: false,\n canSeedRuntimeFiles: false,\n maxActiveJobs: 32,\n};\n\n/** A refusal in the spec's own words: the machine-readable error, and a reason for a developer to read. */\nexport class TorrentFailure extends Error {\n constructor(\n readonly code: string,\n readonly reason?: string,\n /** Fields the failed result also carries, such as the settings beside `revision-conflict`. */\n readonly extra: Readonly<Record<string, unknown>> = {},\n ) {\n super(code);\n }\n}\n\n/** What an adapter's rejection means to an applet. The words name no address and no secret. */\nconst CLIENT_FAILURES: readonly (readonly [prefix: string, code: string, reason: string])[] = [\n ['denied:credentials', 'network-error', \"Your torrent program refused kernl's sign-in.\"],\n ['unavailable:rejected', 'invalid-source', 'Your torrent program declined the torrent.'],\n ['unavailable:not-found', 'job-not-found', 'Your torrent program does not have this torrent.'],\n ['unavailable:unsupported', 'unsupported', 'Your torrent program cannot do that.'],\n];\n\n/**\n * Turns anything thrown while serving a request into a refusal the spec names. An\n * adapter's own message never travels on: only its stable prefix is read.\n *\n * @param error - A {@link TorrentFailure}, or an adapter's rejection.\n * @returns The refusal to answer with.\n * @example\n * ```ts\n * torrentFailureFrom(new Error('unavailable:timeout')).code; // 'network-error'\n * ```\n */\nexport function torrentFailureFrom(error: unknown): TorrentFailure {\n if (error instanceof TorrentFailure) return error;\n const message = String((error as Error).message);\n const known = CLIENT_FAILURES.find(([prefix]) => message.startsWith(prefix));\n return known ? new TorrentFailure(known[1], known[2]) : new TorrentFailure('network-error', UNREACHABLE);\n}\n\n/**\n * Drops the keys whose value is undefined, so an unknown is absent on the wire, never\n * null and never zero.\n *\n * @param value - A record whose unknown fields are undefined.\n * @returns The record without them.\n * @example\n * ```ts\n * definedFields({ jobId: 'tor-1', totalBytes: undefined }); // { jobId: 'tor-1' }\n * ```\n */\nexport function definedFields<T>(value: { [K in keyof T]: T[K] | undefined }): T {\n return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined)) as T;\n}\n\n/**\n * The fields of a failed answer, shaped as the wire table has them for that request.\n *\n * @param type - The request's type.\n * @param message - The request, read only for the job id a failed `remove` repeats.\n * @param failure - The refusal.\n * @returns The fields to send beside `type` and `id`.\n * @example\n * ```ts\n * torrentFailureFields('torrent.status', message, new TorrentFailure('job-not-found')); // { error: 'job-not-found' }\n * ```\n */\nexport function torrentFailureFields(type: string, message: Readonly<Record<string, unknown>>, failure: TorrentFailure): Record<string, unknown> {\n const field = TORRENT_REQUESTS[type] as string;\n if (field !== 'ack' && field !== 'result') return { error: failure.code };\n const jobId = typeof message.jobId === 'string' ? message.jobId : '';\n const body = definedFields({ ok: false, jobId: type === 'torrent.remove' ? jobId : undefined, error: failure.code, reason: failure.reason, ...failure.extra });\n return { [field]: body };\n}\n\ntype Check = (value: unknown) => boolean;\n\nconst isRecord: Check = (value) => typeof value === 'object' && value !== null && !Array.isArray(value) && !ArrayBuffer.isView(value);\nconst isAnything: Check = () => true;\nconst isText: Check = (value) => typeof value === 'string';\nconst isFlag: Check = (value) => typeof value === 'boolean';\nconst isCount: Check = (value) => Number.isSafeInteger(value) && (value as number) >= 0;\nconst isName: Check = (value) => typeof value === 'string' && value.length > 0 && value.length <= 128;\nconst isHash: Check = (value) => typeof value === 'string' && /^[0-9a-f]{40}$/.test(value);\nconst oneOf = (allowed: readonly unknown[]): Check => (value) => allowed.includes(value);\nconst listOf = (check: Check): Check => (value) => Array.isArray(value) && value.every(check);\n\n/**\n * Reads a record strictly: every key present must be a known field holding a value of\n * the right kind, and every required field must be there.\n *\n * @param value - What arrived.\n * @param fields - The fields allowed, each with its check.\n * @param required - The fields that must be present.\n * @returns The record, or undefined when it does not fit.\n * @example\n * ```ts\n * torrentRecord({ deleteData: true }, { deleteData: (value) => typeof value === 'boolean' }); // { deleteData: true }\n * ```\n */\nexport function torrentRecord(value: unknown, fields: Readonly<Record<string, Check>>, required: readonly string[] = []): Record<string, unknown> | undefined {\n if (!isRecord(value)) return undefined;\n const record = value as Record<string, unknown>;\n const fits = Object.keys(record).every((key) => Object.hasOwn(fields, key) && (record[key] === undefined || (fields[key] as Check)(record[key])));\n return fits && required.every((key) => record[key] !== undefined) ? record : undefined;\n}\n\ninterface Shape {\n readonly fields: Readonly<Record<string, Check>>;\n readonly required?: readonly string[];\n /** What a misfit is refused as; `invalid-request` unless said. */\n readonly code?: string;\n}\n\nfunction need<T>(value: unknown, shape: Shape): T {\n const record = torrentRecord(value, shape.fields, shape.required);\n if (!record) throw new TorrentFailure(shape.code ?? 'invalid-request');\n return record as T;\n}\n\n/**\n * An id a request must carry as text: a job's, or another request's.\n *\n * @param value - The request's `jobId` or `requestId`.\n * @returns The id.\n * @throws `invalid-request` when it is not text.\n * @example\n * ```ts\n * torrentText(message.jobId);\n * ```\n */\nexport function torrentText(value: unknown): string {\n if (typeof value !== 'string') throw new TorrentFailure('invalid-request');\n return value;\n}\n\n/** A stored job as it is kept between reloads. */\nexport interface StoredTorrentJob {\n readonly applet: string;\n readonly jobId: string;\n readonly infoHash: string;\n /** The id of the connection the torrent was handed to. */\n readonly connection: string;\n readonly mode: TorrentServiceMode;\n readonly revision: number;\n readonly downloadLimit: number;\n readonly uploadLimit: number;\n readonly paused: boolean;\n readonly title?: string;\n}\n\nconst STORED_JOB: Shape = {\n fields: { applet: isText, jobId: isName, infoHash: isHash, connection: isName, mode: oneOf(['download', 'download-and-seed']), revision: isCount, downloadLimit: isCount, uploadLimit: isCount, paused: isFlag, title: isText },\n required: ['applet', 'jobId', 'infoHash', 'connection', 'mode', 'revision', 'downloadLimit', 'uploadLimit', 'paused'],\n};\n\n/**\n * Reads one job back out of storage, trusting nothing about it.\n *\n * @param value - One entry of the stored list.\n * @returns The job, or undefined when the entry is damaged.\n * @example\n * ```ts\n * readStoredTorrentJob({ applet: 'films' }); // undefined\n * ```\n */\nexport function readStoredTorrentJob(value: unknown): StoredTorrentJob | undefined {\n return torrentRecord(value, STORED_JOB.fields, STORED_JOB.required) as StoredTorrentJob | undefined;\n}\n\n/** A validated `add`: what to hand the program, and the job to keep for it. */\nexport interface TorrentAddPlan {\n readonly source: TorrentClientSource;\n readonly infoHash: string;\n /** The torrent's name when the source says one; a magnet's is only what the applet claims. */\n readonly title?: string;\n readonly jobId?: string;\n readonly mode: TorrentServiceMode;\n readonly retention: TorrentRetention;\n readonly startPaused: boolean;\n readonly downloadLimit: number;\n readonly uploadLimit: number;\n}\n\ntype Identified = Pick<TorrentAddPlan, 'source' | 'infoHash' | 'title'>;\n\ninterface ClaimedHashes {\n readonly v1?: string;\n readonly v2?: string;\n}\n\nconst HASHES: Shape = { fields: { v1: isHash, v2: (value) => typeof value === 'string' && /^[0-9a-f]{64}$/.test(value) }, code: 'invalid-infohash' };\n\n/**\n * A magnet link that names a torrent by its hash and, when there is one, its name.\n * Nothing else goes in: no tracker, no web seed, no peer.\n *\n * @param infoHash - The v1 info hash, 40 lowercase hexadecimal characters.\n * @param name - The display name, or empty text for none.\n * @returns The magnet link.\n * @example\n * ```ts\n * torrentMagnet('ab'.repeat(20), 'Night Mix'); // 'magnet:?xt=urn:btih:abab…&dn=Night%20Mix'\n * ```\n */\nexport function torrentMagnet(infoHash: string, name: string): string {\n return `magnet:?xt=urn:btih:${infoHash}${name ? `&dn=${encodeURIComponent(name)}` : ''}`;\n}\n\nfunction readMagnet(source: Readonly<Record<string, unknown>>): Identified {\n const magnet = source.magnet;\n if (typeof magnet !== 'string' || magnet.length > MAX_MAGNET_LENGTH) throw new TorrentFailure('invalid-magnet');\n const query = new URLSearchParams(magnet.slice(magnet.indexOf('?') + 1));\n try {\n return definedFields<Identified>({ source: { kind: 'magnet', magnet }, infoHash: magnetInfoHash(magnet), title: query.get('dn')?.slice(0, MAX_TITLE_LENGTH) || undefined });\n } catch {\n const onlyV2 = query.getAll('xt').some((topic) => topic.toLowerCase().startsWith('urn:btmh:'));\n throw onlyV2 ? new TorrentFailure('unsupported-format', V1_ONLY) : new TorrentFailure('invalid-magnet');\n }\n}\n\nfunction readInfoHash(source: Readonly<Record<string, unknown>>): Identified {\n const hashes = need<ClaimedHashes>(source.hashes, HASHES);\n if (hashes.v1 === undefined) throw hashes.v2 === undefined ? new TorrentFailure('invalid-infohash') : new TorrentFailure('unsupported-format', V1_ONLY);\n return { source: { kind: 'magnet', magnet: torrentMagnet(hashes.v1, '') }, infoHash: hashes.v1 };\n}\n\nconst BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;\nconst isByte: Check = (value) => Number.isInteger(value) && (value as number) >= 0 && (value as number) <= 255;\n\n/**\n * The bytes of a `.torrent` in any form a page can post: a typed array or buffer (what\n * structured clone carries), a list of byte values, or padded base64 text.\n */\nfunction metainfoBytes(value: unknown): Uint8Array {\n const limit = TORRENT_CAPABILITIES.maxMetainfoBytes;\n if ((typeof value === 'string' || Array.isArray(value)) && value.length > limit * 2) throw new TorrentFailure('too-large');\n if (ArrayBuffer.isView(value)) return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);\n if (value instanceof ArrayBuffer) return new Uint8Array(value);\n if (listOf(isByte)(value)) return Uint8Array.from(value as number[]);\n if (typeof value === 'string' && BASE64.test(value)) return Uint8Array.from(atob(value), (character) => character.charCodeAt(0));\n throw new TorrentFailure('invalid-source');\n}\n\nasync function readMetainfo(source: Readonly<Record<string, unknown>>): Promise<Identified> {\n const bytes = metainfoBytes(source.metainfo);\n if (bytes.byteLength > TORRENT_CAPABILITIES.maxMetainfoBytes) throw new TorrentFailure('too-large');\n const metainfo = await readTorrentMetainfo(bytes).catch((error: Error) => {\n throw error.message.startsWith('invalid:metainfo-format') ? new TorrentFailure('unsupported-format', V1_ONLY) : new TorrentFailure('invalid-source');\n });\n const claimed = source.hashes === undefined ? { v1: metainfo.infoHash } : need<ClaimedHashes>(source.hashes, HASHES);\n if (claimed.v2 !== undefined || claimed.v1 !== metainfo.infoHash) throw new TorrentFailure('hash-mismatch');\n return { source: { kind: 'metainfo', bytes }, infoHash: metainfo.infoHash, title: metainfo.name.slice(0, MAX_TITLE_LENGTH) };\n}\n\nfunction readFileSet(): never {\n throw new TorrentFailure('unsupported-source', 'kernl cannot hand your files to your torrent program.');\n}\n\nconst SOURCES: Readonly<Record<string, { readonly field: string; readonly read: (source: Readonly<Record<string, unknown>>) => Identified | Promise<Identified> }>> = {\n magnet: { field: 'magnet', read: readMagnet },\n infohash: { field: 'hashes', read: readInfoHash },\n metainfo: { field: 'metainfo', read: readMetainfo },\n 'runtime-file-set': { field: 'runtimeFileSetId', read: readFileSet },\n};\n\n/** A `.torrent` may come with the hash the applet expects it to have; nothing else rides beside the selected field. */\nfunction readSource(value: unknown): Identified | Promise<Identified> {\n const source = need<Record<string, unknown>>(value, { fields: { sourceType: isText, magnet: isAnything, hashes: isAnything, metainfo: isAnything, runtimeFileSetId: isAnything }, required: ['sourceType'], code: 'invalid-source' });\n const type = source.sourceType as string;\n const kind = Object.hasOwn(SOURCES, type) ? SOURCES[type] : undefined;\n const allowed = ['sourceType', kind?.field, type === 'metainfo' ? 'hashes' : undefined];\n const stray = Object.keys(source).some((key) => source[key] !== undefined && !allowed.includes(key));\n if (!kind || source[kind.field] === undefined || stray) throw new TorrentFailure('invalid-source');\n return kind.read(source);\n}\n\ninterface AddOptions {\n readonly mode?: string;\n readonly transport?: string;\n readonly startPaused?: boolean;\n readonly seedAfterComplete?: boolean;\n readonly downloadLimitBytesPerSecond?: number;\n readonly uploadLimitBytesPerSecond?: number;\n readonly storage?: string;\n readonly trackers?: readonly string[];\n readonly webSeeds?: readonly string[];\n readonly fileSelection?: object;\n readonly retention?: TorrentRetention;\n readonly createFormat?: string;\n}\n\nconst ADD_OPTIONS: Shape = {\n fields: {\n mode: oneOf(MODES),\n transport: isText,\n startPaused: isFlag,\n seedAfterComplete: isFlag,\n downloadLimitBytesPerSecond: isCount,\n uploadLimitBytesPerSecond: isCount,\n storage: oneOf(['temporary', 'persistent', 'user-selected']),\n trackers: listOf(isText),\n webSeeds: listOf(isText),\n fileSelection: isRecord,\n retention: oneOf(['session', 'persistent']),\n createFormat: oneOf(['v1', 'v2', 'hybrid']),\n },\n};\n\n/** The well-formed options kernl still has to turn down, first match wins. */\nfunction refusedOption(options: AddOptions, mode: string): readonly [boolean, string, string?] | undefined {\n const refusals: readonly (readonly [boolean, string, string?])[] = [\n [mode === 'seed', 'unsupported-mode', 'kernl cannot hand your files to your torrent program.'],\n [!['auto', 'bittorrent'].includes(options.transport ?? 'auto'), 'unsupported-transport'],\n [(options.storage ?? 'persistent') !== 'persistent', 'storage-denied', 'Your torrent program chooses where files go.'],\n [options.trackers !== undefined || options.webSeeds !== undefined, 'unsupported-setting', 'Trackers and web seeds travel in the magnet link or the torrent file.'],\n [options.fileSelection !== undefined, 'unsupported', 'Choose files with selectFiles once the file list is known.'],\n [options.createFormat !== undefined, 'invalid-request'],\n [options.seedAfterComplete !== undefined && options.seedAfterComplete !== (mode === 'download-and-seed'), 'invalid-request'],\n ];\n return refusals.find(([refused]) => refused);\n}\n\n/**\n * Validates an `add` request down to what the program is handed. Nothing is sent\n * anywhere: a source is checked, bounded and identified here first.\n *\n * @param value - The request's `request` field.\n * @returns The plan.\n * @throws A {@link TorrentFailure} naming the first thing wrong.\n * @example\n * ```ts\n * const plan = await planTorrentAdd({ source: { sourceType: 'infohash', hashes: { v1: 'ab'.repeat(20) } } });\n * plan.mode; // 'download'\n * ```\n */\nexport async function planTorrentAdd(value: unknown): Promise<TorrentAddPlan> {\n const request = need<{ source: unknown; jobId?: string; options?: unknown }>(value, { fields: { source: isRecord, jobId: isName, options: isRecord }, required: ['source'] });\n const options = need<AddOptions>(request.options ?? {}, ADD_OPTIONS);\n const identified = await readSource(request.source);\n const mode = options.mode ?? 'download';\n const refused = refusedOption(options, mode);\n if (refused) throw new TorrentFailure(refused[1], refused[2]);\n return definedFields({\n ...identified,\n jobId: request.jobId,\n mode: mode as TorrentServiceMode,\n retention: options.retention ?? 'session',\n startPaused: options.startPaused ?? false,\n downloadLimit: options.downloadLimitBytesPerSecond ?? 0,\n uploadLimit: options.uploadLimitBytesPerSecond ?? 0,\n });\n}\n\n/** A validated `update`. */\nexport interface TorrentUpdatePlan {\n readonly jobId: string;\n readonly expectedRevision: number;\n readonly downloadLimit?: number;\n readonly uploadLimit?: number;\n readonly seedAfterComplete?: boolean;\n}\n\nconst PATCH: Shape = { fields: { downloadLimitBytesPerSecond: isCount, uploadLimitBytesPerSecond: isCount, seedAfterComplete: isFlag } };\n\n/**\n * Validates an `update` request. A setting kernl cannot change, trackers and web seeds\n * among them, is `unsupported-setting`; a known setting with a bad value is `invalid-request`.\n *\n * @param value - The request's `request` field.\n * @returns The plan.\n * @throws A {@link TorrentFailure} naming the first thing wrong.\n * @example\n * ```ts\n * planTorrentUpdate({ jobId: 'tor-1', expectedRevision: 0, patch: { uploadLimitBytesPerSecond: 500000 } }).uploadLimit; // 500000\n * ```\n */\nexport function planTorrentUpdate(value: unknown): TorrentUpdatePlan {\n const request = need<{ jobId: string; expectedRevision: number; patch: Record<string, unknown> }>(value, {\n fields: { jobId: isText, expectedRevision: isCount, patch: isRecord },\n required: ['jobId', 'expectedRevision', 'patch'],\n });\n const names = Object.keys(request.patch);\n if (names.some((name) => !Object.hasOwn(PATCH.fields, name))) throw new TorrentFailure('unsupported-setting');\n const patch = need<{ downloadLimitBytesPerSecond?: number; uploadLimitBytesPerSecond?: number; seedAfterComplete?: boolean }>(request.patch, PATCH);\n if (names.length === 0) throw new TorrentFailure('invalid-request');\n return definedFields({\n jobId: request.jobId,\n expectedRevision: request.expectedRevision,\n downloadLimit: patch.downloadLimitBytesPerSecond,\n uploadLimit: patch.uploadLimitBytesPerSecond,\n seedAfterComplete: patch.seedAfterComplete,\n });\n}\n\n/** The files a `selectFiles` names, and the priority to give them. */\nexport interface TorrentSelectionPlan {\n readonly indexes: readonly number[];\n readonly paths: readonly string[];\n /** -1, 0 or 1, as the program takes it. */\n readonly priority?: number;\n}\n\n/**\n * Validates a file selection. It must name at least one file, by index or by path.\n *\n * @param value - The request's `selection` field.\n * @returns The files named and their priority, narrowed to low, normal or high.\n * @throws `invalid-request` when malformed or empty.\n * @example\n * ```ts\n * planTorrentSelection({ indexes: [0], priority: 7 }); // { indexes: [0], paths: [], priority: 1 }\n * ```\n */\nexport function planTorrentSelection(value: unknown): TorrentSelectionPlan {\n const selection = need<{ indexes?: number[]; paths?: string[]; priority?: number }>(value, { fields: { indexes: listOf(isCount), paths: listOf(isText), priority: Number.isSafeInteger } });\n const plan = { indexes: selection.indexes ?? [], paths: selection.paths ?? [] };\n if (plan.indexes.length + plan.paths.length === 0) throw new TorrentFailure('invalid-request');\n return selection.priority === undefined ? plan : { ...plan, priority: Math.sign(selection.priority) };\n}\n\n/** A validated `jobs` filter; an absent list lets everything through. */\nexport interface TorrentFilterPlan {\n readonly states?: readonly string[];\n readonly modes?: readonly string[];\n}\n\n/**\n * Validates the optional filter of a `jobs` request.\n *\n * @param value - The request's `filter` field.\n * @returns The filter.\n * @throws `invalid-request` when malformed.\n * @example\n * ```ts\n * planTorrentFilter({ states: ['seeding'] });\n * ```\n */\nexport function planTorrentFilter(value: unknown): TorrentFilterPlan {\n return need<TorrentFilterPlan>(value ?? {}, { fields: { states: listOf(oneOf(STATES)), modes: listOf(oneOf(MODES)) } });\n}\n\n/**\n * Validates the optional options of a `remove` request.\n *\n * @param value - The request's `options` field.\n * @returns Whether the applet asked for the downloaded data to go too.\n * @throws `invalid-request` when malformed.\n * @example\n * ```ts\n * wantsTorrentDataDeleted({ deleteData: true }); // true\n * ```\n */\nexport function wantsTorrentDataDeleted(value: unknown): boolean {\n return need<{ deleteData?: boolean }>(value ?? {}, { fields: { deleteData: isFlag } }).deleteData === true;\n}\n","import type { TorrentClientFile, TorrentClientJob } from '@kernlize/bridges';\nimport type { TorrentFileStatus, TorrentJobState, TorrentJobStatus, TorrentJobSummary, TorrentRetention, TorrentSettings } from '@napplet/core';\nimport { createNamespacedStore } from '../persistence/store.js';\nimport type { StorageLike } from '../types.js';\nimport { definedFields, readStoredTorrentJob, TorrentFailure, torrentMagnet, type StoredTorrentJob, type TorrentAddPlan, type TorrentServiceMode } from './torrent-wire.js';\nimport type { DownloadQuestion } from './types.js';\n\n/** One applet's hold on one torrent in the person's program. */\nexport interface TorrentJobRecord {\n /** The owning applet's name; a job is never visible to another. */\n readonly applet: string;\n readonly jobId: string;\n readonly infoHash: string;\n /** The id of the connection the torrent was handed to; every later call goes there, or nowhere. */\n readonly connection: string;\n readonly retention: TorrentRetention;\n /** The window a session job lives and dies with; absent on a persistent job. */\n readonly windowId?: string;\n readonly title?: string;\n mode: TorrentServiceMode;\n revision: number;\n downloadLimit: number;\n uploadLimit: number;\n /** The applet paused it, so a finished download reads `paused`, not `complete`. */\n paused: boolean;\n /** The program no longer has the torrent; the job has ended in `error`. */\n failed: boolean;\n /** Nothing more will happen to it unasked, so it need not be watched. */\n idle: boolean;\n /** What the owning windows were last told, to tell them only what changed. */\n lastState?: TorrentJobState;\n lastNumbers?: string;\n}\n\n/** The jobs the service holds: session jobs in memory, persistent ones also in storage. */\nexport interface TorrentJobs {\n all(): readonly TorrentJobRecord[];\n /** Every job of an applet, whichever window made it. */\n owned(applet: string): readonly TorrentJobRecord[];\n /** The jobs a window may see: its applet's persistent jobs and its own session jobs. */\n visible(applet: string, windowId: string): readonly TorrentJobRecord[];\n /** Keeps a job; a persistent one is written to storage first, and is not kept when that fails. */\n add(record: TorrentJobRecord): void;\n drop(record: TorrentJobRecord): void;\n /** Writes a changed persistent job through to storage. */\n touch(record: TorrentJobRecord): void;\n /** Drops a window's session jobs and returns them. */\n endWindow(windowId: string): readonly TorrentJobRecord[];\n}\n\nconst KEY = 'torrent-jobs:v1';\n\nfunction stored(record: TorrentJobRecord): StoredTorrentJob {\n const { applet, jobId, infoHash, connection, mode, revision, downloadLimit, uploadLimit, paused, title } = record;\n return { applet, jobId, infoHash, connection, mode, revision, downloadLimit, uploadLimit, paused, ...(title === undefined ? {} : { title }) };\n}\n\n/**\n * The service's job records. Persistent jobs are read back from storage here, each one\n * checked field by field: a damaged entry, or a second entry under an id already\n * taken, is dropped instead of trusted.\n *\n * @param storage - Where persistent jobs are kept, under `kernl:torrent-jobs:v1`.\n * @returns The records.\n * @example\n * ```ts\n * const jobs = createTorrentJobs(localStorage);\n * jobs.visible('films', windowId);\n * ```\n */\nexport function createTorrentJobs(storage: StorageLike): TorrentJobs {\n const store = createNamespacedStore(storage, 'kernl');\n let records: TorrentJobRecord[] = [];\n const raw = store.getJson<unknown>(KEY, []);\n for (const entry of Array.isArray(raw) ? raw : []) {\n const job = readStoredTorrentJob(entry);\n if (job && !records.some((record) => record.applet === job.applet && record.jobId === job.jobId)) records.push({ ...job, retention: 'persistent', failed: false, idle: false });\n }\n const write = (kept: readonly TorrentJobRecord[]): void => {\n try {\n store.setJson(KEY, kept.filter((record) => record.retention === 'persistent').map(stored));\n } catch {\n throw new TorrentFailure('storage-denied', 'The job could not be kept.');\n }\n };\n return {\n all: () => [...records],\n owned: (applet) => records.filter((record) => record.applet === applet),\n visible: (applet, windowId) => records.filter((record) => record.applet === applet && (record.windowId ?? windowId) === windowId),\n add(record) {\n if (record.retention === 'persistent') write([...records, record]);\n records.push(record);\n },\n drop(record) {\n records = records.filter((kept) => kept !== record);\n if (record.retention === 'persistent') write(records);\n },\n touch(record) {\n if (record.retention === 'persistent') write(records);\n },\n endWindow(windowId) {\n const ended = records.filter((record) => record.windowId === windowId);\n records = records.filter((record) => record.windowId !== windowId);\n return ended;\n },\n };\n}\n\n/**\n * Whether the program has all of a torrent: it is sharing it, or holds it stopped and whole.\n *\n * @param job - The torrent as the program reports it.\n * @returns True once nothing is left to download.\n * @example\n * ```ts\n * torrentFinished(job) && record.mode === 'download'; // kernl pauses it\n * ```\n */\nexport function torrentFinished(job: TorrentClientJob): boolean {\n return job.state === 'seeding' || job.state === 'complete' || (job.state === 'paused' && job.progress === 1);\n}\n\n/** A finished torrent in `download` mode is `complete`, or `paused` when the applet paused it; everything else is the program's word. */\nfunction stateOf(record: TorrentJobRecord, job: TorrentClientJob): TorrentJobState {\n if (!torrentFinished(job) || record.mode !== 'download') return job.state;\n return record.paused ? 'paused' : 'complete';\n}\n\n/**\n * A job's current settings. Tracker and web-seed lists are never disclosed, because a\n * tracker address can carry the person's private passkey.\n *\n * @param record - The job.\n * @returns Its settings and revision.\n * @example\n * ```ts\n * torrentJobSettings(record).endpointsRedacted; // true\n * ```\n */\nexport function torrentJobSettings(record: TorrentJobRecord): TorrentSettings {\n return {\n revision: record.revision,\n downloadLimitBytesPerSecond: record.downloadLimit,\n uploadLimitBytesPerSecond: record.uploadLimit,\n seedAfterComplete: record.mode === 'download-and-seed',\n endpointsRedacted: true,\n };\n}\n\n/**\n * A job's status snapshot from what the program reports now. What the program does not\n * know yet (size, progress, time left) is left out, never filled with zero.\n *\n * @param record - The job.\n * @param job - The torrent as the program reports it.\n * @returns The status.\n * @example\n * ```ts\n * torrentJobStatus(record, job).ratio; // uploaded / downloaded, or 0\n * ```\n */\nexport function torrentJobStatus(record: TorrentJobRecord, job: TorrentClientJob): TorrentJobStatus {\n return definedFields({\n ok: true as const,\n jobId: record.jobId,\n state: stateOf(record, job),\n mode: record.mode,\n transport: 'bittorrent',\n hashes: { v1: record.infoHash },\n downloadedBytes: job.downloadedBytes,\n uploadedBytes: job.uploadedBytes,\n totalBytes: job.totalBytes,\n progress: job.progress,\n downloadRate: job.downloadRate,\n uploadRate: job.uploadRate,\n ratio: job.downloadedBytes > 0 ? job.uploadedBytes / job.downloadedBytes : 0,\n peers: { peers: job.peers, seeds: job.seeds, leeches: job.leeches },\n title: job.name || undefined,\n etaSeconds: job.etaSeconds,\n settings: torrentJobSettings(record),\n retention: record.retention,\n });\n}\n\n/**\n * A job's line in a `jobs` listing. A job whose torrent the program no longer has is\n * listed in `error`, so the applet can still find and remove it.\n *\n * @param record - The job.\n * @param job - The torrent as the program reports it, or undefined when it is gone.\n * @returns The summary.\n * @example\n * ```ts\n * torrentJobSummary(record, undefined).state; // 'error'\n * ```\n */\nexport function torrentJobSummary(record: TorrentJobRecord, job: TorrentClientJob | undefined): TorrentJobSummary {\n const base = { jobId: record.jobId, mode: record.mode, transport: 'bittorrent', hashes: { v1: record.infoHash }, retention: record.retention };\n if (!job) return { ...base, state: 'error', downloadRate: 0, uploadRate: 0, ratio: 0 };\n const { state, progress, downloadRate, uploadRate, ratio, title } = torrentJobStatus(record, job);\n return definedFields({ ...base, state, progress, downloadRate, uploadRate, ratio, title });\n}\n\n/**\n * One file's status as the wire has it.\n *\n * @param file - The file as the program reports it.\n * @returns The file status; an empty file counts as whole.\n * @example\n * ```ts\n * torrentFileStatus({ index: 0, path: 'a.bin', size: 10, downloadedBytes: 5, selected: true, priority: 0 }).progress; // 0.5\n * ```\n */\nexport function torrentFileStatus(file: TorrentClientFile): TorrentFileStatus {\n const { index, path, size, selected, priority, downloadedBytes } = file;\n return { index, path, size, selected, priority, downloadedBytes, progress: size > 0 ? downloadedBytes / size : 1 };\n}\n\n/**\n * What `metadata` answers for a torrent the program has read: its identity and a magnet\n * built from the hash and name alone, with no tracker in it.\n *\n * @param job - The torrent as the program reports it.\n * @returns The metadata result.\n * @throws `metadata-unavailable` while the program has not read the torrent, or cannot say whether it is private.\n * @example\n * ```ts\n * torrentMetadata(job).magnet; // 'magnet:?xt=urn:btih:…&dn=Night%20Mix'\n * ```\n */\nexport function torrentMetadata(job: TorrentClientJob): Record<string, unknown> {\n if (job.state === 'metadata' || job.private === undefined) throw new TorrentFailure('metadata-unavailable');\n return definedFields({\n ok: true,\n format: 'v1',\n hashes: { v1: job.infoHash },\n name: job.name,\n private: job.private,\n magnet: torrentMagnet(job.infoHash, job.name),\n endpointsRedacted: true,\n metainfoReady: false,\n });\n}\n\nconst PEERS_SEE = { label: 'Other people see', value: 'The network address of the machine running your torrent program' };\n\nfunction naming(subject: { readonly title?: string; readonly infoHash: string }): DownloadQuestion['lines'] {\n return [...(subject.title ? [{ label: 'Name', value: subject.title }] : []), { label: 'Torrent', value: subject.infoHash }];\n}\n\n/**\n * The question put to the person before a torrent is handed to their program.\n *\n * @param plan - The validated request.\n * @param program - The label of the connection the torrent goes to.\n * @returns What is added, where, how long it shares, who sees what, and what closing the applet does.\n * @example\n * ```ts\n * describeTorrentAdd(plan, 'Home').title; // 'Add a torrent to Home'\n * ```\n */\nexport function describeTorrentAdd(plan: TorrentAddPlan, program: string): DownloadQuestion {\n return {\n kind: 'add',\n title: `Add a torrent to ${program}`,\n lines: [\n ...naming(plan),\n { label: 'Program', value: program },\n { label: 'Sharing', value: plan.mode === 'download' ? 'Stops when the download finishes' : 'Keeps sharing with other people after the download finishes' },\n PEERS_SEE,\n { label: 'If you close this applet', value: plan.retention === 'session' ? 'The download pauses' : 'The download carries on in your torrent program' },\n ],\n };\n}\n\n/**\n * The question put to the person before downloaded files are deleted.\n *\n * @param record - The job being removed.\n * @returns What is deleted, and where.\n * @example\n * ```ts\n * describeTorrentDelete(record).kind; // 'delete'\n * ```\n */\nexport function describeTorrentDelete(record: TorrentJobRecord): DownloadQuestion {\n return {\n kind: 'delete',\n title: 'Delete the torrent\\'s files',\n lines: [...naming(record), { label: 'Deletes', value: 'The files this torrent downloaded, on the machine running your torrent program' }],\n };\n}\n","import type { ServiceRuntimeContext } from '@kehto/runtime';\nimport type { TorrentClient, TorrentClientJob } from '@kernlize/bridges';\nimport type { ConnectionRouting, RoutedClient } from './connections.js';\nimport type { NappletMessage, TorrentJobStatus } from '@napplet/core';\nimport {\n createTorrentJobs,\n describeTorrentAdd,\n describeTorrentDelete,\n torrentFileStatus,\n torrentFinished,\n torrentJobSettings,\n torrentJobStatus,\n torrentJobSummary,\n torrentMetadata,\n type TorrentJobRecord,\n type TorrentJobs,\n} from './torrent-jobs.js';\nimport {\n planTorrentAdd,\n planTorrentFilter,\n planTorrentSelection,\n planTorrentUpdate,\n TORRENT_CAPABILITIES,\n TORRENT_PUSHES,\n TORRENT_REQUESTS,\n TorrentFailure,\n torrentFailureFields,\n torrentFailureFrom,\n torrentText,\n wantsTorrentDataDeleted,\n type TorrentAddPlan,\n} from './torrent-wire.js';\nimport type { DownloadService, DownloadServiceDeps } from './types.js';\n\n/** What the torrent service needs from the shell. */\nexport interface TorrentServiceOptions extends DownloadServiceDeps {\n /** The person's torrent connections, read on every request: new torrents go to one, and each job stays on its own. */\n readonly connections: ConnectionRouting<TorrentClient>;\n /** How often jobs with a live window are refreshed and pushed; 2000 ms by default. */\n readonly pollMs?: number;\n}\n\n/** A NIP-5D envelope with its payload fields, which kehto's own type leaves to each domain. */\ntype Envelope = NappletMessage & Record<string, unknown>;\n\n/** One request on its way through: who sent it, for which applet, and what it says. */\ninterface Call {\n readonly windowId: string;\n readonly applet: string;\n readonly message: Readonly<Record<string, unknown>>;\n}\n\n/** Everything one service instance holds. */\ninterface Engine {\n readonly options: TorrentServiceOptions;\n readonly jobs: TorrentJobs;\n /** Live windows that have spoken, each with its applet. */\n readonly windows: Map<string, string>;\n readonly runtimes: ServiceRuntimeContext[];\n /** The end of the queue every call to the program waits in. */\n tail: Promise<unknown>;\n timer: ReturnType<typeof setTimeout> | undefined;\n /** The connections that could not be reached at the last refresh, whose windows were told. */\n readonly unreachable: Set<string>;\n disposed: boolean;\n}\n\nconst NOT_SET_UP = 'No torrent program is set up.';\nconst NO_LONGER = 'That torrent program is no longer set up.';\nconst GONE = 'Your torrent program no longer has this torrent.';\n\n/** Runs work after everything queued before it, whether that succeeded or not. */\nfunction serial<T>(engine: Engine, work: () => Promise<T>): Promise<T> {\n const run = engine.tail.then(work);\n engine.tail = run.catch(() => undefined);\n return run;\n}\n\n/** The connection a job's torrent was handed to, while it can still serve. */\nconst routeOf = (engine: Engine, record: TorrentJobRecord): RoutedClient<TorrentClient> | undefined => engine.options.connections.byId(record.connection);\n\n/** The client of a job's own connection; `source-unavailable` once the person removed it or it is locked. */\nfunction clientOf(engine: Engine, record: TorrentJobRecord): TorrentClient {\n const routed = routeOf(engine, record);\n if (!routed) throw new TorrentFailure('source-unavailable', NO_LONGER);\n return routed.client;\n}\n\n/** A session job speaks to its own window; a persistent job to every live window of its applet. */\nfunction recipients(engine: Engine, record: TorrentJobRecord): readonly string[] {\n if (record.windowId !== undefined) return [record.windowId];\n return [...engine.windows].filter(([, applet]) => applet === record.applet).map(([windowId]) => windowId);\n}\n\nfunction push(engine: Engine, record: TorrentJobRecord, message: Envelope): void {\n for (const windowId of recipients(engine, record)) for (const runtime of engine.runtimes) runtime.sendToEligibleNapplet(windowId, message);\n}\n\n/** The other jobs holding the same torrent on the same connection; the same torrent elsewhere is another program's copy. */\nfunction sharers(engine: Engine, record: TorrentJobRecord): readonly TorrentJobRecord[] {\n return engine.jobs.all().filter((other) => other !== record && other.connection === record.connection && other.infoHash === record.infoHash);\n}\n\nfunction visible(engine: Engine, call: Call, jobId: string): TorrentJobRecord {\n const record = engine.jobs.visible(call.applet, call.windowId).find((candidate) => candidate.jobId === jobId);\n if (!record) throw new TorrentFailure('job-not-found');\n return record;\n}\n\n/**\n * Brings a job in line with what the program reports: ends it when the torrent is gone,\n * takes a limit changed in the program as a new revision, and pauses a finished\n * torrent that no owner wants shared.\n */\nasync function settle(engine: Engine, record: TorrentJobRecord, job: TorrentClientJob | undefined, client: TorrentClient): Promise<TorrentClientJob | undefined> {\n if (record.failed || !job) {\n record.failed = true;\n return undefined;\n }\n if (job.downloadLimit !== record.downloadLimit || job.uploadLimit !== record.uploadLimit) {\n Object.assign(record, { downloadLimit: job.downloadLimit, uploadLimit: job.uploadLimit, revision: record.revision + 1 });\n engine.jobs.touch(record);\n }\n const wanted = [record, ...sharers(engine, record)].some((owner) => !owner.failed && owner.mode === 'download-and-seed');\n if (job.state === 'seeding' && !wanted) await client.pause(record.infoHash);\n return job;\n}\n\nasync function current(engine: Engine, record: TorrentJobRecord): Promise<TorrentClientJob> {\n const client = clientOf(engine, record);\n const job = await settle(engine, record, await client.get(record.infoHash), client);\n if (!job) throw new TorrentFailure('source-unavailable', GONE);\n return job;\n}\n\nasync function view(engine: Engine, record: TorrentJobRecord): Promise<TorrentJobStatus> {\n return torrentJobStatus(record, await current(engine, record));\n}\n\n/** Tells a job's windows what changed since they were last told: its state, or else its numbers. */\nfunction report(engine: Engine, record: TorrentJobRecord, job: TorrentClientJob | undefined): void {\n const jobId = record.jobId;\n if (!job) {\n push(engine, record, { type: 'torrent.error', jobId, error: 'source-unavailable', reason: GONE });\n push(engine, record, { type: 'torrent.state', jobId, state: 'error' });\n record.idle = true;\n return;\n }\n const status = torrentJobStatus(record, job);\n const numbers = JSON.stringify({ ...status, state: undefined });\n if (status.state !== record.lastState) push(engine, record, { type: 'torrent.state', jobId, state: status.state, status });\n else if (numbers !== record.lastNumbers) push(engine, record, { type: 'torrent.progress', jobId, status });\n // The program's own words can hold a tracker address with a passkey in it, so they are not passed on.\n if (status.state === 'error' && record.lastState !== 'error') push(engine, record, { type: 'torrent.error', jobId, error: 'network-error', reason: 'Your torrent program reported a problem with this torrent.' });\n Object.assign(record, { lastState: status.state, lastNumbers: numbers, idle: status.state === 'complete' || status.state === 'error' });\n}\n\n/**\n * Tells a job's windows its connection is gone. The job is not ended: a locked connection\n * signed in to again serves it once more, so it is only left unwatched until asked about.\n */\nfunction orphan(engine: Engine, record: TorrentJobRecord): void {\n push(engine, record, { type: 'torrent.error', jobId: record.jobId, error: 'source-unavailable', reason: NO_LONGER });\n push(engine, record, { type: 'torrent.state', jobId: record.jobId, state: 'error' });\n Object.assign(record, { lastState: 'error', idle: true });\n}\n\nfunction watched(engine: Engine): readonly TorrentJobRecord[] {\n return engine.jobs.all().filter((record) => !record.idle && recipients(engine, record).length > 0);\n}\n\n/** One reading of one connection for its watched jobs. An outage is told once per connection, not every tick. */\nasync function pollConnection(engine: Engine, id: string, records: readonly TorrentJobRecord[]): Promise<void> {\n const routed = engine.options.connections.byId(id);\n if (!routed) return records.forEach((record) => orphan(engine, record));\n try {\n const list = await routed.client.list();\n for (const record of records) report(engine, record, await settle(engine, record, list.find((job) => job.infoHash === record.infoHash), routed.client));\n engine.unreachable.delete(id);\n } catch (error) {\n const reason = torrentFailureFrom(error).reason as string;\n if (!engine.unreachable.has(id)) for (const record of records) push(engine, record, { type: 'torrent.error', jobId: record.jobId, error: 'network-error', reason });\n engine.unreachable.add(id);\n }\n}\n\n/** One `list()` per connection that has watched jobs. */\nasync function poll(engine: Engine): Promise<void> {\n const byConnection = new Map<string, TorrentJobRecord[]>();\n for (const record of watched(engine)) byConnection.set(record.connection, [...(byConnection.get(record.connection) ?? []), record]);\n for (const [id, records] of byConnection) await pollConnection(engine, id, records);\n}\n\n/** Keeps the one timer running only while some live window has a job that can still change. */\nfunction arm(engine: Engine): void {\n if (engine.disposed || engine.timer !== undefined || watched(engine).length === 0) return;\n engine.timer = setTimeout(() => {\n engine.timer = undefined;\n void serial(engine, () => poll(engine)).then(() => arm(engine));\n }, engine.options.pollMs ?? 2000);\n}\n\n/** Runs one change or reading of a job the caller may see, in turn behind everything queued before it. */\nfunction onJob<T>(engine: Engine, call: Call, jobId: unknown, act: (record: TorrentJobRecord, client: TorrentClient) => Promise<T>): Promise<T> {\n const id = torrentText(jobId);\n return serial(engine, async () => {\n const record = visible(engine, call, id);\n const client = clientOf(engine, record);\n record.idle = false;\n return act(record, client);\n });\n}\n\nfunction admit(engine: Engine, applet: string, plan: TorrentAddPlan): void {\n const owned = engine.jobs.owned(applet);\n if (owned.some((record) => record.jobId === plan.jobId || record.infoHash === plan.infoHash)) throw new TorrentFailure('job-conflict', 'This applet already has that job or that torrent.');\n if (owned.length >= (TORRENT_CAPABILITIES.maxActiveJobs as number)) throw new TorrentFailure('quota-exceeded');\n}\n\n/**\n * Hands the torrent to the program once the person has said yes. The job is written\n * down first. Limits are set while the torrent is still paused, so it never runs\n * unlimited first; if that fails it stays paused in the program and no job is kept.\n */\nasync function start(engine: Engine, call: Call, plan: TorrentAddPlan, connection: string): Promise<Record<string, unknown>> {\n if (engine.windows.get(call.windowId) !== call.applet) throw new TorrentFailure('policy-denied');\n admit(engine, call.applet, plan);\n // The person said yes to this connection; if it went meanwhile, the torrent goes nowhere else.\n const client = engine.options.connections.byId(connection)?.client;\n if (!client) throw new TorrentFailure('unsupported-transport', NO_LONGER);\n const { infoHash, mode, retention, title, downloadLimit, uploadLimit, startPaused } = plan;\n const state = startPaused ? 'paused' : 'queued';\n const record: TorrentJobRecord = {\n applet: call.applet,\n jobId: plan.jobId ?? `tor-${crypto.randomUUID()}`,\n infoHash, connection, retention, mode, downloadLimit, uploadLimit,\n revision: 0,\n paused: startPaused,\n failed: false,\n idle: false,\n lastState: state,\n ...(retention === 'session' ? { windowId: call.windowId } : {}),\n ...(title === undefined ? {} : { title }),\n };\n engine.jobs.add(record);\n try {\n const limited = downloadLimit > 0 || uploadLimit > 0;\n await client.add(plan.source, { paused: startPaused || limited });\n if (limited) await client.setLimits(infoHash, { downloadLimit, uploadLimit });\n if (limited && !startPaused) await client.resume(infoHash);\n } catch (error) {\n engine.jobs.drop(record);\n throw error;\n }\n return { ok: true, jobId: record.jobId, state };\n}\n\n/** Where a new torrent goes: the connection a job already holds it on, so it is never fetched twice, else the person's default. */\nfunction target(engine: Engine, plan: TorrentAddPlan): RoutedClient<TorrentClient> {\n const holder = engine.jobs.all().find((record) => record.infoHash === plan.infoHash && routeOf(engine, record) !== undefined);\n const routed = (holder && routeOf(engine, holder)) ?? engine.options.connections.preferred();\n if (!routed) throw new TorrentFailure('unsupported-transport', NOT_SET_UP);\n return routed;\n}\n\nasync function add(engine: Engine, call: Call): Promise<Record<string, unknown>> {\n const plan = await planTorrentAdd(call.message.request);\n const { connection } = target(engine, plan);\n admit(engine, call.applet, plan);\n if (!(await engine.options.ask(call.windowId, describeTorrentAdd(plan, connection.label)))) throw new TorrentFailure('user-denied');\n return serial(engine, () => start(engine, call, plan, connection.id));\n}\n\n/** Takes the torrent out of its program when no other job holds it there; resolves whether the program had it. */\nasync function takeOut(engine: Engine, record: TorrentJobRecord, deleteData: boolean): Promise<boolean> {\n const routed = routeOf(engine, record);\n if (!routed || sharers(engine, record).length > 0) return false;\n const job = await routed.client.get(record.infoHash);\n if (job) await routed.client.remove(record.infoHash, deleteData);\n return job !== undefined;\n}\n\n/**\n * A torrent another job still holds stays in the program with its data, whatever was\n * asked. Data is deleted only when the person said yes to this very removal. A job whose\n * connection is gone is only forgotten: kernl cannot remove anything from a program it no\n * longer knows, so nobody is asked about files.\n */\nasync function remove(engine: Engine, call: Call): Promise<Record<string, unknown>> {\n const jobId = torrentText(call.message.jobId);\n const wanted = wantsTorrentDataDeleted(call.message.options);\n const held = visible(engine, call, jobId);\n const asking = wanted && routeOf(engine, held) !== undefined && sharers(engine, held).length === 0;\n if (asking && !(await engine.options.ask(call.windowId, describeTorrentDelete(held)))) throw new TorrentFailure('user-denied');\n return serial(engine, async () => {\n const record = visible(engine, call, jobId);\n const removed = await takeOut(engine, record, asking);\n engine.jobs.drop(record);\n return { ok: true, jobId, deletedData: asking && removed };\n });\n}\n\n/** The files named are fetched and every other file is skipped; a name the torrent does not have refuses the whole request. */\nfunction selectFiles(engine: Engine, call: Call): Promise<TorrentJobStatus> {\n const selection = planTorrentSelection(call.message.selection);\n return onJob(engine, call, call.message.jobId, async (record, client) => {\n const files = await client.files(record.infoHash);\n if (files.length === 0) throw new TorrentFailure('metadata-unavailable');\n const all = files.map((file) => file.index);\n const named = selection.paths.map((path) => files.find((file) => file.path === path)?.index ?? -1);\n const wanted = [...new Set([...selection.indexes, ...named])];\n if (wanted.some((index) => !all.includes(index))) throw new TorrentFailure('invalid-request');\n const skipped = all.filter((index) => !wanted.includes(index));\n await client.selectFiles(record.infoHash, wanted, { selected: true, ...(selection.priority === undefined ? {} : { priority: selection.priority }) });\n if (skipped.length > 0) await client.selectFiles(record.infoHash, skipped, { selected: false });\n return view(engine, record);\n });\n}\n\n/**\n * Limits go to the program; whether to keep sharing is kernl's own to remember. A\n * finished download asked to share starts at once unless the applet paused it; one\n * asked to stop sharing is paused at the next refresh.\n */\nfunction update(engine: Engine, call: Call): Promise<Record<string, unknown>> {\n const plan = planTorrentUpdate(call.message.request);\n return onJob(engine, call, plan.jobId, async (record, client) => {\n const job = await current(engine, record);\n if (plan.expectedRevision !== record.revision) throw new TorrentFailure('revision-conflict', undefined, { settings: torrentJobSettings(record) });\n const downloadLimit = plan.downloadLimit ?? record.downloadLimit;\n const uploadLimit = plan.uploadLimit ?? record.uploadLimit;\n const mode = (plan.seedAfterComplete ?? record.mode === 'download-and-seed') ? 'download-and-seed' : 'download';\n const limitsChange = downloadLimit !== record.downloadLimit || uploadLimit !== record.uploadLimit;\n if (!limitsChange && mode === record.mode) return { ok: true, settings: torrentJobSettings(record) };\n if (limitsChange) await client.setLimits(record.infoHash, { downloadLimit, uploadLimit });\n const startsSharing = mode === 'download-and-seed' && record.mode === 'download' && torrentFinished(job) && !record.paused;\n if (startsSharing) await client.resume(record.infoHash);\n Object.assign(record, { downloadLimit, uploadLimit, mode, revision: record.revision + 1 });\n engine.jobs.touch(record);\n return { ok: true, settings: torrentJobSettings(record) };\n });\n}\n\nfunction setPaused(engine: Engine, call: Call, paused: boolean): Promise<TorrentJobStatus> {\n return onJob(engine, call, call.message.jobId, async (record, client) => {\n await (paused ? client.pause(record.infoHash) : client.resume(record.infoHash));\n record.paused = paused;\n engine.jobs.touch(record);\n return view(engine, record);\n });\n}\n\n/** A job's line, reading its connection's list once per request; a job whose connection is gone is listed in `error`. */\nasync function summarise(engine: Engine, record: TorrentJobRecord, lists: Map<string, Promise<readonly TorrentClientJob[]>>) {\n const routed = routeOf(engine, record);\n if (!routed) return torrentJobSummary(record, undefined);\n const reported = lists.get(record.connection) ?? routed.client.list();\n lists.set(record.connection, reported);\n return torrentJobSummary(record, await settle(engine, record, (await reported).find((job) => job.infoHash === record.infoHash), routed.client));\n}\n\n/** An applet with no jobs is answered without troubling any program. */\nfunction list(engine: Engine, call: Call): Promise<unknown> {\n const filter = planTorrentFilter(call.message.filter);\n return serial(engine, async () => {\n const lists = new Map<string, Promise<readonly TorrentClientJob[]>>();\n const summaries = [];\n for (const record of engine.jobs.visible(call.applet, call.windowId)) summaries.push(await summarise(engine, record, lists));\n return summaries.filter((summary) => (filter.states ?? [summary.state]).includes(summary.state) && (filter.modes ?? [summary.mode]).includes(summary.mode));\n });\n}\n\n/** Nothing an applet can cancel is ever pending here, so there is never anything to stop. */\nasync function cancel(_engine: Engine, call: Call): Promise<Record<string, unknown>> {\n torrentText(call.message.requestId);\n return { ok: true, cancelled: false };\n}\n\nasync function unsupported(): Promise<never> {\n throw new TorrentFailure('unsupported', 'kernl drives a torrent program and cannot reach its files.');\n}\n\nconst OPERATIONS: Readonly<Record<string, (engine: Engine, call: Call) => Promise<unknown>>> = {\n 'torrent.capabilities': async (engine) => (engine.options.connections.all().length > 0 ? TORRENT_CAPABILITIES : { ...TORRENT_CAPABILITIES, transports: [], modes: [] }),\n 'torrent.add': add,\n 'torrent.status': (engine, call) => onJob(engine, call, call.message.jobId, (record) => view(engine, record)),\n 'torrent.jobs': list,\n 'torrent.files': (engine, call) => onJob(engine, call, call.message.jobId, async (record, client) => (await client.files(record.infoHash)).map(torrentFileStatus)),\n 'torrent.selectFiles': selectFiles,\n 'torrent.pause': (engine, call) => setPaused(engine, call, true),\n 'torrent.resume': (engine, call) => setPaused(engine, call, false),\n 'torrent.remove': remove,\n 'torrent.metadata': (engine, call) => onJob(engine, call, call.message.jobId, async (record) => torrentMetadata(await current(engine, record))),\n 'torrent.update': update,\n 'torrent.cancel': cancel,\n 'torrent.pickFiles': unsupported,\n 'torrent.read': unsupported,\n 'torrent.exportMetainfo': unsupported,\n 'torrent.saveFile': unsupported,\n 'torrent.openFile': unsupported,\n};\n\n/** Answers one request with exactly one result, in the shape the wire table gives its type. */\nfunction answer(engine: Engine, windowId: string, request: Envelope, send: (message: NappletMessage) => void): void {\n const { type, id } = request;\n const serve = async (): Promise<unknown> => {\n const applet = engine.options.ownerOf(windowId);\n if (applet === undefined) throw new TorrentFailure('policy-denied');\n engine.windows.set(windowId, applet);\n return (OPERATIONS[type] as (engine: Engine, call: Call) => Promise<unknown>)(engine, { windowId, applet, message: request });\n };\n const fields = serve().then(\n (value): Record<string, unknown> => ({ [TORRENT_REQUESTS[type] as string]: value }),\n (error: unknown) => torrentFailureFields(type, request, torrentFailureFrom(error)),\n );\n void fields.then((payload) => {\n const result: Envelope = { type: `${type}.result`, id, ...payload };\n send(result);\n arm(engine);\n });\n}\n\n/** A session job ends with its window: its torrent is paused in its own program, never removed, unless another job still holds it there. */\nfunction end(engine: Engine, windowId: string): void {\n engine.windows.delete(windowId);\n const ended = engine.jobs.endWindow(windowId);\n if (ended.length === 0) return;\n const pauseOrphans = async (): Promise<void> => {\n for (const record of ended) {\n const routed = routeOf(engine, record);\n if (routed && sharers(engine, record).length === 0) await routed.client.pause(record.infoHash);\n }\n };\n void serial(engine, pauseOrphans).catch(() => undefined);\n}\n\nfunction declared(types: readonly string[]): Record<string, null> {\n return Object.fromEntries(types.map((type) => [type, null]));\n}\n\n/**\n * The `torrent` service: applets download through the torrent program the person\n * already runs. kernl reaches that program over its own API and cannot read its files,\n * so everything that would hand an applet file contents answers `unsupported`, and the\n * program, not kernl, decides where files go.\n *\n * A job is one applet's hold on one torrent. The person is asked before every add and\n * before any deletion. A session job is paused in the program when its window ends; a\n * persistent job is kept in storage and found again by a later window of the same\n * applet. kernl never removes a torrent, or its data, that it was not asked to. Every\n * call to the program runs one after another, so a removal always wins over the\n * changes queued behind it, and one timer tells live windows what changed.\n *\n * The person may set up several torrent programs (D-053). A new torrent goes to the one a\n * job already holds it on, else to the person's default, and the question names it; every\n * later call for the job goes to that connection alone, and a job whose connection was\n * removed or is locked answers `source-unavailable` and can still be removed.\n *\n * @param options - The shell's hooks, the person's torrent connections and the refresh interval.\n * @returns The handler to register as `torrent`, and `dispose`.\n * @example\n * ```ts\n * const torrents = createTorrentService({ appletOf, ownerOf, ask, storage: localStorage, connections: programs.routing('torrent') });\n * registry.torrent = torrents.handler;\n * ```\n */\nexport function createTorrentService(options: TorrentServiceOptions): DownloadService {\n const engine: Engine = { options, jobs: createTorrentJobs(options.storage), windows: new Map(), runtimes: [], tail: Promise.resolve(), timer: undefined, unreachable: new Set(), disposed: false };\n return {\n handler: {\n descriptor: { name: 'torrent', version: '1.0.0', description: \"Torrent downloads through the person's own torrent program\" },\n messageCapabilities: declared(Object.keys(TORRENT_REQUESTS)),\n pushCapabilities: declared(TORRENT_PUSHES),\n onRegistered(context) {\n engine.runtimes.push(context);\n },\n onUnregistered() {\n engine.runtimes.length = 0;\n },\n handleMessage(windowId, message, send) {\n const request = message as Envelope;\n if (typeof request.id === 'string' && Object.hasOwn(OPERATIONS, request.type)) answer(engine, windowId, request, send);\n },\n onWindowDestroyed: (windowId) => end(engine, windowId),\n onPermissionRevoked: (windowId) => end(engine, windowId),\n },\n dispose() {\n engine.disposed = true;\n clearTimeout(engine.timer);\n for (const windowId of engine.windows.keys()) end(engine, windowId);\n },\n };\n}\n","import type { ServiceRegistry } from '@kehto/runtime';\nimport type { PlannedExtensions } from './applets/plan.js';\nimport { DOWNLOAD_BINDINGS, supportsDomainBindings } from './downloads/bindings.js';\nimport { createDownloadClients, type DownloadClients } from './downloads/download-clients.js';\nimport { createNzbService } from './downloads/nzb-service.js';\nimport { createSoulseekService } from './downloads/soulseek-service.js';\nimport { createTorrentService } from './downloads/torrent-service.js';\nimport type { DownloadQuestion, DownloadService, DownloadServiceDeps } from './downloads/types.js';\nimport type { SecretsProvider } from './secrets/secrets.js';\nimport type { AppletIdentity, ConsentSummary, DownloadsOptions, KernlHost } from './types.js';\n\n/**\n * The domains kernl serves by driving the person's own download programs, in the order they are offered.\n *\n * @example\n * ```ts\n * DOWNLOAD_DOMAINS.includes('nzb'); // true\n * ```\n */\nexport const DOWNLOAD_DOMAINS: readonly string[] = Object.freeze(['torrent', 'nzb', 'soulseek']);\n\n/** What the download services need from the composed shell. */\nexport interface KernlDownloadsDeps {\n readonly host: Pick<KernlHost, 'storage' | 'presentConsent' | 'now'>;\n readonly options: DownloadsOptions | undefined;\n /** Where the programs' passwords and keys are kept. */\n readonly secrets: SecretsProvider;\n /** The verified applet a window runs, or undefined. */\n readonly identityOf: (windowId: string) => AppletIdentity | undefined;\n /** The catalogue id of the applet a window runs, which what it starts is kept under. */\n readonly ownerOf: (windowId: string) => string | undefined;\n /** Fetches an NZB an applet named by address, under the shell's own fetch policy. */\n readonly fetchDocument: (url: string, signal: AbortSignal) => Promise<Uint8Array>;\n}\n\n/** The download programs' settings, the services over them when they can be offered, and their teardown. */\nexport interface KernlDownloads {\n readonly programs: DownloadClients;\n /** The handlers to register, keyed by domain; empty when the domains cannot be offered. */\n readonly services: ServiceRegistry;\n /** What planning adds to an applet's environment; undefined when the domains cannot be offered. */\n readonly extensions: PlannedExtensions | undefined;\n dispose(): void;\n}\n\n/**\n * A download service's question as the host's consent prompt takes it. Starting something\n * that shows peers the address of the machine doing the transfer is `direct`; erasing files\n * is `destructive`; an archive download, which only the person's own servers see, is `routine`.\n *\n * @param question - What the service asks.\n * @param applet - The applet it asks for.\n * @param exposesAddress - Whether peers learn a network address from what is being started.\n * @returns The summary the host renders.\n * @example\n * ```ts\n * describeDownloadQuestion({ kind: 'delete', title: 'Delete the files', lines: [] }, identity, true).severity; // 'destructive'\n * ```\n */\nexport function describeDownloadQuestion(question: DownloadQuestion, applet: AppletIdentity, exposesAddress: boolean): ConsentSummary {\n const started = exposesAddress ? 'direct' : 'routine';\n return {\n title: question.title,\n severity: question.kind === 'delete' ? 'destructive' : started,\n lines: question.lines.map((line) => ({ label: line.label, after: line.value })),\n applet,\n };\n}\n\n/**\n * The three download domains over the programs the person set up (D-050).\n *\n * The settings are always there, so the person can set a program up before any applet asks\n * for it. The services are created, and the domains offered, only when kehto's prelude can\n * bind a domain it does not build in (`supportsDomainBindings`), or the host says its own\n * does (`downloads.offer`). Every question a service has goes to the person through the\n * host's consent prompt, in the name of the applet that caused it; a window that is no\n * longer a live applet is answered no without asking.\n *\n * @param deps - Host, options, the secrets provider, the window-to-applet lookup and the NZB fetcher.\n * @returns Settings, handlers, the planning extension and teardown.\n * @example\n * ```ts\n * const downloads = createKernlDownloads({ host, options: undefined, secrets: createStorageSecrets(host.storage), identityOf, ownerOf, fetchDocument });\n * Object.assign(services.registry, downloads.services);\n * ```\n */\nexport function createKernlDownloads(deps: KernlDownloadsDeps): KernlDownloads {\n const { host, options } = deps;\n const programs = createDownloadClients({\n storage: host.storage,\n secrets: deps.secrets,\n ...(options?.pageScheme ? { pageScheme: options.pageScheme } : {}),\n ...(options?.fetch ? { fetch: options.fetch } : {}),\n });\n if (!(options?.offer ?? supportsDomainBindings())) return { programs, services: {}, extensions: undefined, dispose: () => undefined };\n\n const base = (exposesAddress: boolean): DownloadServiceDeps => ({\n appletOf: deps.identityOf,\n ownerOf: deps.ownerOf,\n storage: host.storage,\n ...(host.now ? { now: host.now.bind(host) } : {}),\n ask(windowId, question) {\n const applet = deps.identityOf(windowId);\n if (!applet) return Promise.resolve(false);\n return new Promise((resolve) => host.presentConsent({ summary: describeDownloadQuestion(question, applet, exposesAddress), resolve }));\n },\n });\n // An NZB downloader is keyed by its connection's routing key, so a handle issued for jobs at an old address never reaches the new one's.\n const nzb = programs.routing('nzb');\n const created: Readonly<Record<string, DownloadService>> = {\n torrent: createTorrentService({ ...base(true), connections: programs.routing('torrent') }),\n nzb: createNzbService({ ...base(false), downloaders: () => nzb.all().map(({ connection, client }) => ({ key: connection.routingKey, label: connection.label, client })), fetchDocument: deps.fetchDocument }),\n soulseek: createSoulseekService({ ...base(true), connections: programs.routing('soulseek') }),\n };\n return {\n programs,\n services: Object.fromEntries(Object.entries(created).map(([domain, service]) => [domain, service.handler])),\n extensions: { domains: DOWNLOAD_DOMAINS, bindings: DOWNLOAD_BINDINGS },\n dispose: () => Object.values(created).forEach((service) => service.dispose()),\n };\n}\n","import type { Subject } from 'rxjs';\nimport type { PermissionAdapter, Runtime } from '@kehto/runtime';\nimport { permissionRuleSubject } from '@kehto/firewall';\nimport type { GuardEvent } from '@kernlize/guard';\nimport type { AppletSummary, FirewallApplet, KernlHost } from './types.js';\nimport type { MountedApplet } from './applets/mount.js';\nimport type { GuardPipeline } from './guard/pipeline.js';\nimport { createRuntimeRateLimiter, toGuardEvent } from './guard/runtime-rate-limit.js';\nimport { createAppletAdmissions, type AppletAdmissions } from './firewall/admission.js';\nimport { createFirewall, type KernlFirewall } from './firewall/firewall.js';\nimport { createFirewallPermissions } from './firewall/permissions.js';\nimport { createFirewallRules } from './firewall/rules.js';\n\n/** The legacy rate gate's stored configuration; nothing reads it since the firewall took over (D-056). */\nconst RETIRED_STORAGE_KEYS: readonly string[] = ['kernl:firewall:v1'];\n\n/** What the shell's firewall needs from the rest of the shell. */\nexport interface ShellFirewallParts {\n readonly host: KernlHost;\n /** Its configuration is the guard profile in force, whose budgets the runtime charges against. */\n readonly pipeline: Pick<GuardPipeline, 'config'>;\n /** Live handles keyed by window id; a budget report names the applet its window runs. */\n readonly handles: ReadonlyMap<string, MountedApplet>;\n readonly guardEvents$: Subject<GuardEvent>;\n}\n\n/** The firewall's host side before kehto's runtime exists, and the rest once it does. */\nexport interface ShellFirewall {\n /** For `ShellAdapter.permissions`. */\n readonly permissions: PermissionAdapter;\n /** Tell the firewall which applet a plan is for, so its questions can name it. */\n remember(summary: AppletSummary): void;\n /** The firewall the host sees and the admissions the lifecycle asks, over the runtime kehto built with `permissions`. */\n attach(runtime: Runtime): { readonly firewall: KernlFirewall; readonly admissions: AppletAdmissions };\n}\n\n/** The applet across versions and the exact code, as both a summary and kehto's principal name them. */\nfunction plannedKey(subject: string, hash: string): string {\n return `${subject}\\n${hash}`;\n}\n\n/**\n * Assemble one shell's firewall (D-056): the person's rules, their stored\n * answers, the question put through the host, and the guard profile's budgets\n * for what the runtime carries out.\n *\n * kehto's runtime is built from the adapter this hands `permissions` to, so\n * the surface the host and the lifecycle use comes afterwards, from `attach`.\n * The legacy rate gate's stored configuration is removed on the way.\n *\n * @param parts - Host, guard pipeline, live handles and the guard event stream.\n * @returns The permission adapter, the applet register and `attach`.\n * @example\n * ```ts\n * const guarding = createShellFirewall({ host, pipeline, handles, guardEvents$ });\n * const bridge = createShellBridge({ ...adapter, permissions: guarding.permissions });\n * const { firewall, admissions } = guarding.attach(bridge.runtime);\n * ```\n */\nexport function createShellFirewall({ host, pipeline, handles, guardEvents$ }: ShellFirewallParts): ShellFirewall {\n for (const key of RETIRED_STORAGE_KEYS) host.storage.removeItem(key);\n const rules = createFirewallRules(host.storage);\n const now = host.now ? host.now.bind(host) : Date.now;\n const presentApproval = host.presentApproval?.bind(host);\n const planned = new Map<string, FirewallApplet>();\n let firewall: KernlFirewall | undefined;\n const asking: Pick<KernlHost, 'presentApproval'> = presentApproval ? {\n presentApproval: (prompt) => presentApproval({\n ...prompt,\n resolve(choice) {\n prompt.resolve(choice);\n // kehto stores the answer in the turn after this one; then the answers in force have changed.\n setTimeout(() => firewall?.touch(), 0);\n },\n }),\n } : {};\n const permissions = createFirewallPermissions({\n host: { storage: host.storage, notify: (notice) => host.notify(notice), ...(host.now ? { now } : {}), ...asking },\n rules,\n appletOf: (principal) => planned.get(plannedKey(permissionRuleSubject(principal), principal.artifactHash)),\n rateLimiter: createRuntimeRateLimiter(() => pipeline.config),\n onRateLimit: (event) => guardEvents$.next(toGuardEvent(event, handles.get(event.windowId)?.summary.identity.dTag ?? 'unknown', now())),\n });\n return {\n permissions,\n remember(summary) {\n const { catalogId } = summary.manifest;\n planned.set(plannedKey(catalogId, summary.identity.hash), { title: summary.title, catalogId, identity: summary.identity });\n },\n attach(runtime) {\n // `permissions` is always configured here, so the runtime always has its management surface.\n firewall = createFirewall({ rules, permissions: runtime.permissions as NonNullable<Runtime['permissions']> });\n return { firewall, admissions: createAppletAdmissions(runtime, now) };\n },\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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MAAK,EAAG;AAClC,UAAM,QAAQ,UAAUA,OAAM,QAAQ,IAAI,KAAK;AAC/C,QAAI,QAAQ,EAAG,QAAO,KAAK,EAAE,OAAO,MAAM,CAAC;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,OAAOC,MAAK,OAAO,EAAE,OAAO,OAAAA,OAAM,EAAE,EAC1C,KAAK,CAAC,GAAG,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,cAAc,EAAE,KAAK,CAAC,EAClE,MAAM,GAAG,KAAK;AAAA,EACnB;AACF;;;AhGlHO,IAAM,eAAe;AAWrB,IAAM,0BAAkC,6BAA6B;","names":["update","current","BehaviorSubject","newest","text","query","current","BehaviorSubject","relays","list","filter","BehaviorSubject","map","normalizeRelayUrl","relays","settle","from","relayUrls","kinds","filter","target","finish","map","finished","relays","resolve","answer","from","BehaviorSubject","relays","relayUrls","lastValueFrom","map","relays","text","text","coordinate","lastValueFrom","map","merge","switchMap","timer","toArray","unique","relays","newest","current","filter","switchMap","timer","merge","map","relays","lastValueFrom","toArray","newest","text","Subject","listeners","BehaviorSubject","present","resolve","timer","failure","BehaviorSubject","finished","BehaviorSubject","record","list","take","count","BehaviorSubject","admit","visible","resolveWindow","classifyEnvelope","BehaviorSubject","target","discard","Subject","map","target","Subject","STORAGE_KEY","Subject","stored","record","current","getInboxes","getOutboxes","text","kinds","lastValueFrom","timer","toArray","isReplaceable","lastValueFrom","timer","toArray","isReplaceable","resolveApplet","resolve","STORAGE_KEY","kinds","getConversationParticipants","PrivateKeySigner","unixNow","end","summarize","query","lastValueFrom","load","list","relays","relays","unixNow","signerOf","current","query","PrivateKeySigner","kinds","getConversationParticipants","relays","target","kinds","mergeRelaySets","verifyEvent","getConversationParticipants","verifyEvent","getConversationParticipants","kinds","mergeRelaySets","verifyEvent","text","start","CAPABILITIES","relays","filter","verifyEvent","signed","signerOf","usable","from","current","query","unixNow","lastValueFrom","toArray","relays","lastValueFrom","toArray","bytesToHex","kinds","mergeRelaySets","text","start","bytesToHex","mergeRelaySets","filter","relays","start","kinds","latest","group","CAPABILITIES","unixNow","signerOf","query","torrent","query","page","BehaviorSubject","catchError","EMPTY","map","of","switchMap","unixNow","stateFor","of","catchError","EMPTY","switchMap","map","BehaviorSubject","unixNow","relays","from","resolve","stored","STORAGE_KEY","read","getProfileContent","unixNow","FOLLOWS","add","current","target","text","lastValueFrom","map","takeUntil","catchError","EMPTY","lastValueFrom","takeUntil","timer","decodePointer","HEX_KEY","text","decodePointer","lastValueFrom","takeUntil","timer","catchError","EMPTY","catchError","distinctUntilChanged","EMPTY","endWith","filter","firstValueFrom","ignoreElements","map","merge","Observable","switchMap","take","timer","getOutboxes","getProfileContent","HEX_KEY","getProfileContent","load","relays","map","getOutboxes","filter","take","switchMap","Observable","distinctUntilChanged","timer","card","catchError","EMPTY","ignoreElements","endWith","firstValueFrom","merge","map","takeUntil","lastValueFrom","relays","filter","end","PrivateKeySigner","target","page","BehaviorSubject","STORAGE_KEY","HEX_KEY","text","BehaviorSubject","lastValueFrom","takeUntil","timer","toArray","decodeEventPointer","verifyEvent","parseJson","text","decodeEventPointer","relays","filter","lastValueFrom","takeUntil","timer","toArray","verifyEvent","document","list","reference","newest","verifyEvent","HEX_KEY","invalid","resolve","finish","timer","session","shaped","filter","relays","end","verifyEvent","recipients","located","text","relays","view","verifyEvent","located","resolve","verifyEvent","TIERS","verifyEvent","originRegistry","record","keyOf","originRegistry","relays","BehaviorSubject","map","of","Subject","Subscription","switchMap","createGuardConfig","renderNappletNamespacePrelude","BehaviorSubject","checkClientEndpoint","page","stored","STORAGE_KEY","page","checkClientEndpoint","clientOf","BehaviorSubject","load","current","sound","load","list","decode","declared","scan","end","text","read","STORE_KEY","record","keyOf","load","orphan","stored","MAX_TEXT_LENGTH","text","isObject","read","page","failure","call","document","successor","encoder","text","call","visible","page","REVOKED","call","answer","ignore","record","call","invalid","isText","query","text","daemon","TERMINAL","record","remove","ignore","answer","discard","call","stateOf","clientOf","yes","end","query","record","UNREACHABLE","failure","isRecord","isText","isCount","oneOf","record","need","source","query","ADD_OPTIONS","record","serial","record","push","call","settle","list","filter","OPERATIONS","resolve","nzb","lastValueFrom","Subject","takeUntil","timer","toArray","verifyEvent","HEX_64","tag","newest","verifyEvent","current","Subject","lastValueFrom","takeUntil","timer","toArray","resolve","BehaviorSubject","STORAGE_KEY","toCatalogEntry","stored","BehaviorSubject","applet","installed","rank","FAILURES","UNREACHABLE","installed","list","auditTime","catchError","EMPTY","lastValueFrom","map","merge","share","takeUntil","tap","timer","reference","deletion","relays","EMPTY","takeUntil","timer","catchError","tap","merge","auditTime","map","share","lastValueFrom","Subscription","switchMap","map","of","relays","appletOf","record","resolve","createGuardConfig","Subject","BehaviorSubject","from","text","query","count"]}
|