Browser-agnostic protocol engine for the napplet protocol.
Alpha status: Kehto is an early runtime toolkit for a draft NIP-5D protocol. NAP contracts and runtime APIs are not final; treat this package as current implementation guidance, not as a stable protocol guarantee.
pnpm add @kehto/runtime
Peers admit @napplet/core >=0.32.0 <0.46.0 and @napplet/nap
>=0.32.0 <0.46.0; the runtime does not import the NAP-LLM types, so it keeps the older floor. Host packages develop and build on core 0.45.0 / nap 0.45.0; fixture napplets stay on the exact 0.32.0 line (shim 0.30.0, sdk 0.28.0, vite-plugin 0.16.2). The exact fixture-line convention contracts are core 0.32.0 /
nap 0.32.0 from NAP-INTENT authority 5ac0490461ca6fec2f0d2e45b4835cf9bc08de24,
napplet/web#199 source 3037200c932488f14f7f369b8583c39c9c16510a / merge
b3f0007867eac109fa4917fac9c285d3b7cc6155, and Version Packages #198 release
source dc1d24153c759152b6ba31a6ec9bea967798f2df.
@kehto/runtime is Kehto's NIP-5D protocol engine. It owns every incoming napplet message, gates it through the ACL enforcement layer, routes it to the correct NAP handler, and emits the corresponding reply envelope.
The runtime is built around the current draft dispatch contract from @napplet/core — createDispatch() + registerNap() — so routing is declarative, not a hand-rolled switch. It covers the NIP-5D domains currently supported by Kehto:
identity.getProfile, identity.getFollows, identity.getPublicKey, …inc.channel.*, inc.emit, cross-napplet pub/subkeys.forward, keys.action, keys.bindmedia.* playback & transport controlnotify.send, notify.channel.register, badge/permission flowsrelay.publish, relay.publishEncrypted, relay.subscribedm.status, dm.conversations, dm.messages, dm.send, runtime service dispatchfs.info, pickers, metadata, byte I/O, mutations, watches, runtime service dispatchstorage.get/set/remove/keys with quota enforcementtheme.get and automatic recipient-authorized theme.changedSigning is shell-mediated inside relay.publish / relay.publishEncrypted (NIP-44 default, NIP-04 opt-in). The legacy signer domain is dissolved — napplets never see a host-injected nostr object and cannot call signer-sign RPCs directly.
Hosts can call runtime.aclState.setStateQuota(pubkey, dTag, aggregateHash, bytes)
to update the exact principal's live storage limit. bytes must be an integer
from zero through Number.MAX_SAFE_INTEGER; malformed input throws RangeError
before changing policy. Call aclState.persist() separately to save the quota.
The default remains 524,288 bytes. Grants and block status are preserved.
The existing storage handler consumes this same quota across shared and instance storage for that principal, counting UTF-8 bytes including scoped storage keys. Lowering a quota preserves stored values; writes that exceed the new limit fail until data is removed or the host increases the quota. Zero prevents nonempty storage writes while reads/removals remain subject to their existing ACL checks.
This host administration API conforms to NAP-STORAGE draft PR #3 at
4f4cf0ca7ecbd24c284a5d63bcd85e3de6af37ca.
It adds no napplet-callable quota setter or wire field.
aclState.getAllEntries() and getEntry() return dTag and aggregateHash
alongside the policy fields. Use these values with keyed ACL methods; two
principals with identical grants still have distinct identities after reload.
Enumeration keeps pubkey: '' because ACL identity is keyed by dTag and artifact
hash. Returned objects and capability arrays are detached from the owned state.
for (const entry of runtime.aclState.getAllEntries()) {
runtime.aclState.revoke(entry.pubkey, entry.dTag, entry.aggregateHash, 'relay:read');
}
This host API adds no protocol messages and does not change serialized ACL keys.
Custom AclEntryExternal producers must populate the two required identity fields.
ACL mutations update live policy immediately. Revoke/block observers run
synchronously after that change, before any explicit save. aclState.persist()
returns true when the persistence backend completes and false if it throws.
A failed save never rolls back live policy or reactivates retired subscriptions;
a newly loaded container can still see the last successfully saved policy.
aclState.clear() resets live policy to its configured default and attempts to
clear storage, returning the same success boolean. A failed clear leaves that
live reset in place and old durable data unchanged. Retry persistence or clearing
after handling the backend failure. These results report the synchronous backend
contract, not physical disk durability. Hosts must not swallow backend errors if
they want the container to detect failure.
runtime.aclState.revoke('', dTag, aggregateHash, 'relay:read');
if (!runtime.aclState.persist()) {
showSaveError('Access is revoked for this session, but the policy was not saved.');
}
Runtime destruction remains best-effort; hosts requiring an actionable save
result should call persist() before teardown. This host API policy is outside
the NAP wire contract. No old-use warning can detect callers ignoring a return
value; see the compatibility register.
Revoking relay:read or blocking a principal immediately retires ordinary relay
subscriptions in every window with that exact dTag and aggregate hash. The
runtime closes registered relay/cache backends and direct adapter subscriptions,
sends relay.closed with reason denied: relay:read, and suppresses queued events
and EOSE callbacks. Regranting access requires a new subscription; old callbacks
remain invalid even if the same subId is reused. Other principals, other artifact
versions, and revocation of unrelated capabilities leave subscriptions active.
This host policy conforms to NAP-RELAY draft PR #2 at
9f30b3505335a52c574ff570576687d6467021ff,
which permits ACL enforcement and policy-driven subscription termination.
The publish path follows draft NAP-RELAY PR #2 at
0be8abce18beb46ca37bd4ddd042f58d30b4eedc.
A napplet submits an EventTemplate; the runtime obtains the active
shell-owned signer, signs once, and gives only the resulting NostrEvent to
the relay backend. Success returns exactly one correlated
relay.publish.result with ok: true, the full signed event, and eventId.
Signing, replay, relay, and service failures return ok: false plus error
and are never buffered as successful local publications.
AuthAdapter.getSigner(windowId?) receives the originating runtime window when
one exists. Kehto forwards that context as a policy mechanism; it does not
decide whether a host prompts once, remembers a narrowly scoped approval, or
refuses the request. Hosts that do not need caller-aware signer policy can
ignore the optional argument.
The released @napplet/nap@0.32.0 SDK accepts EventTemplate, while its
RelayPublishMessage.event declaration still says NostrEvent; Kehto records
that mismatch as upstream package drift and follows the NAP wire direction.
Configure RuntimeAdapter.permissions and a source-bound permissionPrincipal
before accepting relay.subscribe.relay or Kehto's existing relay.query.relay
extension. A hint that selects network transport is rejected when operation
authority is absent. Unhinted host-tier routing remains available for migration
and emits FW-RELAY-NETWORK-LEGACY-001 once per runtime instance on network use.
Local-only mock and shell-event reads remain quiet.
The runtime validates WebSocket URLs, rejects credentials and fragments, and
includes each canonical origin in the relay.network permission request.
Subscribe envelopes and destination plans are detached before approval waits.
Execution uses the exact approved relay URLs; revocation and source replacement
retire the pending/live work. A host's explicit allow rule may authorize the
origin without showing a prompt; an interface grant alone cannot do so.
Relay-pool authentication remains a separate host policy. A network-origin grant does not authorize NIP-42 signing. Use a pool without automatic authentication for napplet-directed traffic; Kehto cannot remove authentication hooks installed inside a third-party pool. The built-in Paja pool has no automatic signer. See relay destination policy.
Authority: NAP-RELAY draft napplet/naps#2 at
9f30b3505335a52c574ff570576687d6467021ff. Scoped subscribe is canonical;
query's relay field remains an existing Kehto extension, not a new wire API.
Executing that extension emits KEHTO_COMPAT_RELAY_QUERY_HINT once per runtime;
migrate to scoped relay.subscribe and close after EOSE. Canonical calls stay quiet.
This runtime follows NAP-IDENTITY and NAP-THEME at napplet/naps master
5ac0490461ca6fec2f0d2e45b4835cf9bc08de24.
identity.getPublicKey always yields exactly one correlated
identity.getPublicKey.result; no signer or a signer failure is
pubkey: "". Other supported readonly identity operations yield their
matching result shapes with safe defaults, while unsupported identity actions
are silently ignored.theme.get uses a complete three-color result. For denied or unavailable
reads, Kehto's explicit policy is one fixed non-sensitive normal result with
no error field. This reconciles the draft's error-only example without
emitting theme.*.error or inventing a mixed theme/error payload.Phase 105 adopts the published @napplet/* convention package line; archived
phase records remain history rather than active compatibility guidance.
Kehto follows NAP-INTENT PR #106 at fc121fc264615482143eda86125863d2e1f741a2. The runtime admits source-side intent.invoke,
intent.available, and intent.handlers through the authenticated session and
ACL/firewall boundary. Services validate the normalized queryless convention and
resolve the sender's opaque catalog ID from the trusted source window.
Registered services receive a frozen ServiceRuntimeContext with live-window
facts and recipient-policy-aware sends. Success acknowledges retained delivery
responsibility with ok, archetype, action, convention, and handler.
After current target readiness, the controller sends one intent.deliver with
parent-attested sender and opaque payload. Completion belongs to host observation,
not another source result. No INC carrier is required.
Kehto follows draft NAP-OUTBOX PR #32 at
4589a8f9a16d8aa29b3740e2b3b0cdca11e0976e.
ACL and firewall policy may reject an outbox query, but the rejection stays on
the protocol-defined correlated result wire: outbox.query.result with
events: [] and error. The runtime does not synthesize an
outbox.query.error message.
ACL and legacy Firewall denials answer each recognized request on its owning
NAP's failure wire, never an invented <type>.error. A denied cvm.* request
gets its matching .result with error: "policy denied" (NAP-CVM #31 at
28cf1bdb); relay, outbox, upload, count, notify, dm, fs,
keys, media and config follow their own NAPs, and requests with no defined
reply stay silent (including a denied config.get). The legacy Firewall gate
uses the same rows for common, lists, serial, ble, webrtc, link and
gamepad, which ACL does not gate. The per-type table, refs and
spec-gap decisions are in
RUNTIME-SPEC.md.
The fixture-line @napplet/nap@0.32.0 contract trails PR #106. Host packages
take the intent types from @napplet/core@0.41.0, which @kehto/services
re-exports; see the
conformance policy.
Phase 105 completed released package adoption and persistent installed-manifest controllers for the live Paja host.
The active INC boundary follows merged
naps/NAP-INC.md
on napplet/naps master
377bf939c6c906817084b43dd21d424de646dbc2. The document remains marked
draft, but the merged path is the protocol authority.
The released projection binding converts a convention query to a text payload
map before sending inc.emit. Runtime inc-handler routing then uses an exact
stable convention topic identity, with no query-bearing normalized
wire/discovery identity, prefix/wildcard/query-aware matching, generic or
service-over-INC prefix dispatch, or runtime payload-kind inference. Arbitrary
opaque topic strings, including ? and #, are routed by their complete exact
text. The runtime derives the
runtime-attested endpoint identifier from the registered source; callers never supply a
sender, topic delivery excludes its source, and IDs/payloads are opaque.
target, sender, and peer are runtime-assigned endpoint identifiers: opaque text, one per live registered
endpoint, taken from the injected crypto.randomUUID, and carrying no manifest d tag, artifact hash, window ID,
instance ID, or ordering. An identifier is assigned on first use, lasts until that registration is replaced or
unregistered, and is never reused; a replacement registration is a new endpoint whose old channels close as
peer destroyed. Root and snapshot manifests without a d tag get identifiers like any other endpoint. A d tag is
never resolved as a channel target (KEHTO_INC_DTAG_TARGET_RETIRED in
the compatibility register). Napplets learn a peer
from an attested sender/peer; a host selects one with Runtime.getIncEndpointId(windowId).
// Host peer selection: hand napplet A the endpoint of the window the user picked.
const target = runtime.getIncEndpointId(pickedWindowId);
Migration from @kehto/runtime 0.26 and earlier: stop passing a manifest d tag to inc.channel.open and stop
comparing sender/peer with a d tag. Keep the sender of an inc.event (or a channel peer) and pass that back.
Channels apply open-time authorization only: ACL and target liveness are
checked at inc.channel.open, never per later message. The target receives
inc.channel.opened before the opener result and both sides get symmetric
handles with onOpened, on, and onClosed; early events and terminal closure
are retained in order, bounded overflow closes the channel, and close or endpoint
destruction tears it down deterministically. channel.list is informational
only. Track draft follow-up through
kehto/web#203 and its upstream
resolution reply,
not the obsolete opener-only model.
This is INC documentation only. Phase 104 owns every public #91 NAP-INTENT binding/resolution/delivery change; Phase 105 records the completed released package adoption. Historical changelogs and archived planning are preserved records, not targets for active-surface edits.
Everything plugs into a single factory, createRuntime(), via a RuntimeAdapter hook bag — persistence, relay pool, auth, services, and so on. No DOM, no postMessage, no localStorage: those live in @kehto/shell.
RelayPoolAdapter.publish() may return a promise. The runtime waits for that
promise before reporting publish success, buffers only successful publishes,
and releases failed replay reservations so a deterministic signed event can be
retried without allowing concurrent duplicate publication.
publishToScopedRelay() may similarly return Promise<boolean> when a host
needs transport settlement before reporting the scoped publication outcome.
RuntimeAdapter.aclDefaultPolicy ('permissive' | 'restrictive') sets the ACL
policy for identities with no stored entry. When set, it replaces the policy in
persisted ACL state on load. Stored entries are kept as they are. With
RuntimeAdapter.permissions it's a ceiling: an operation the ACL denies is refused
with no prompt until the host grants the capability.
Hosts opt into temporal protection with an explicitly constructed
PermissionAdapter.rateLimiter or promptRateLimiter from @kehto/rate-limit.
Hold the limiter to change its configuration. legacyFirewall is an explicit
compatibility adapter for hosts without scoped permissions.
PermissionAdapter.defaultDecision(request, missing) lets a host answer a request
no stored decision covers without prompting. allow admits the request without
writing a grant, so the rule is consulted again on every check and a default allow
can't fill the grant table (kehto/web#513); deny refuses, and ask prompts. It runs
before the prompt budget, and stored denials, the ACL ceiling and operation budgets
still apply. Call RuntimePermissions.rulesChanged() after changing the rules so
live work admitted under the old ones closes. DEFAULT_RULE_GRANT_PREFIX is
deprecated (see DEFAULT_RULE_GRANTS in docs/compatibility.md). The rule model (createPermissionRules, resolvePermissionRule,
setPermissionRule) is re-exported from @kehto/firewall.
import { createRuntime } from '@kehto/runtime';
const runtime = createRuntime({
aclPersistence: aclStore,
manifestPersistence: manifestStore,
relayPool: myRelayPoolAdapter,
auth: myAuthAdapter,
// ... further adapter hooks
});
// Incoming NIP-5D draft envelope from a napplet:
runtime.handleMessage('window-1', {
type: 'relay.publish',
id: 'evt-42',
event: { kind: 1, content: 'hello', /* ... */ },
});
createRuntime — primary entry point; Runtime interface typecreateEnforceGate — legacy pubkey-keyed ACL gatecreateNapEnforceGate — NIP-5D windowId-keyed ACL gateresolveCapabilitiesNap — map a NIP-5D envelope to required capabilities (re-exported from @kehto/acl)formatDenialReason — denied: <capability> canonical stringcreateSessionRegistry — bidirectional windowId ↔ SessionEntry storecreateNappKeyRegistry — deprecated alias retained for v1.1 migration consumersunregister(windowId) retires the window's registration, lookup state, and pending
update, including NIP-5D sessions whose pubkey is empty. Repeated calls are safe.
If a newer window owns the same pubkey lookup, that newer entry is preserved;
use getEntryByWindowId to distinguish live windows sharing an empty pubkey.
runtime.sessionRegistry.register(windowId, entry) establishes a fresh trusted
source lifecycle and retires that window's previous initialization burst budget,
including when the host reuses the window ID, timestamp, or entry object. Ordinary
messages and destroyWindow() alone do not renew the budget. The shell registers
only on the first shell.ready for each host-attested source registration, so
duplicate readiness signals cannot bypass the startup limit. Per-napplet rate
limits remain shared across registrations and versions.
Standalone registries accept an optional second onRegister(windowId) callback.
Runtime retires a supplied limiter's startup lifecycle without resetting shared
token budgets. No limiter means there are no temporal counters to retire.
createAclState — persistence-backed wrapper around @kehto/acl statecreateManifestCache — NIP-5A aggregate-hash cache with persistence hookscreateReplayDetector — duplicate-event + timestamp-window guardcreateEventBuffer — ring buffer with subscription deliverymatchesFilter, matchesAnyFilter — pure NIP-01 filter helpersRING_BUFFER_SIZE — default ring buffer capacity constanthandleStorageNap — canonical storage.* NIP-5D handlercleanupNappState — remove persisted state when a napplet window closescreateUnrecognizedTypeDiagnostic — host warning for a dropped type its NAP does not define ([KEHTO_UNRECOGNIZED_MESSAGE_TYPE], once per domain/type, at most UNRECOGNIZED_TYPE_WARNING_LIMIT types per instance, no payloads). NIP-5D requires such messages to get no reply, including on the ACL denial path.routeServiceMessage — policy-free domain selection primitive; never a fallback for untrusted ingressnotifyServiceWindowDestroyed — lifecycle fan-out to every service handlerdm and fs, route through handlers registered with runtime.registerService('<domain>', handler).RuntimeAdapter.services is copied once at creation. Add later services with registerService, and check routing with runtime.hasService('<domain>'). A request for a domain with no handler is ignored on the wire (NIP-5D) and logged once as [KEHTO_UNROUTED_SERVICE_DOMAIN].For domains outside the built-in dispatcher, handlers opt in with an exact
messageCapabilities map (existing ACL capability or explicit null per inbound
type). Runtime.handleMessage requires a live unblocked source, an explicit
isDomainAllowed grant, the declared ACL grant, and firewall admission. Unknown
types and extension policy denials stay silent on the wire. Registration alone
attaches a service; it does not expose or grant a domain. Fixed NAP routes retain
their own authorization. Pending replies are invalidated by service/source
replacement or teardown and recheck current domain/ACL policy. Unsolicited
shell -> napplet pushes into such a domain need an exact pushCapabilities map
(recipient capability or explicit null per push type) and are delivered through
ServiceRuntimeContext.sendToEligibleNapplet under the same source, domain-grant,
and ACL gates; the call's boolean reports whether the push was delivered.
Browser hosts must provide the owning extension contract and inject its granted namespace binding before scripts run. Stock Paja bindings do not inject arbitrary extensions. See Register a service for the complete host contract and spec bounds.
40+ interfaces — including Runtime, RuntimeAdapter, SendToNapplet, RelayPoolAdapter, ServiceHandler, ServiceRegistry, NappletMessage, SessionEntry, AclEntryExternal, AclCheckEvent, and the per-adapter hook types — are exported from ./types.js for host-app integration.
Retained for migration consumers; new integrations should use current NIP-5D envelope types from @napplet/core. Slated for removal once upstream restores those exports.
Re-exported constants cover the v1.1 bus-kind enum, auth event kind, shell bridge URI, protocol version string, the full capability list, destructive-kind set, and the replay window seconds. Re-exported types cover the v1.1 capability union, bus-kind numeric union, and service descriptor shape. See the typedoc API reference below for the exact identifier list and current numeric values.
Full package docs: docs/packages/runtime.md.
Generated API module: docs/api/modules/_kehto_runtime.html (run pnpm docs:api).
MIT
This non-normative guidance defers to the living NAP-GAMEPAD. Services export createGamepadService and browserGamepadOptions; shell exports denyNappletControllerAccess. Paja registers one host reader and denies native gamepad/HID/USB paths before frame execution. Source-bound subscriptions receive immediate full snapshots; only the visible host's input owner gets live controls. Focus loss supplies neutral controls and timestamp zero; unsubscribe, window destruction, and service removal release polling. Non-browser or denied native readers report the proposal's unavailable reasons. See Controller input.
This non-normative guidance defers to the living NAP-LLM (checked at 5e93bdf). Services export createLlmService, LlmServiceError, the provider mappers (OpenAI Chat Completions, OpenAI Responses, Anthropic Messages and Gemini generateContent dialects) and LLM_PROVIDER_PRESETS; shell exports getShellDomainState and the LlmHooks adapter field; acl exports llm:generate. The runtime routes llm.* to one registered service and answers every sanctioned request with exactly one llm.<op>.result, shaping missing-service and ACL failures as { code: 'unsupported' }. Hosts implement LlmConnectionHost; the service enforces schema, handle ownership, a per-window live-handle bound (maxHandlesPerWindow), consent before submission, duplicate ids, cancellation and deadline races, ordered deltas and safe errors, and passes select/authorize a { signal } that withdraws stale prompts. createHttpLlmProvider({ stream: true }) streams provider output into llm.delta as block start/delta/end events. Results carry content parts (text, thinking and tool calls); tool calls and results are validated and relayed, and Kehto never executes one. Advertisement stays binary on the wire while hosts report a third unconfigured state until the user adds a connection. See Language models.
Rate limiting is optional and lives in @kehto/rate-limit, not runtime or Firewall.
Supply PermissionAdapter.rateLimiter and/or promptRateLimiter to opt in;
omitting either installs no default counters or limits for that traffic.
import { createRateLimiter, defaultRateLimitConfig } from '@kehto/rate-limit';
const limiter = createRateLimiter(defaultRateLimitConfig());
const permissions = { ...approvalAdapter, rateLimiter: limiter };
limiter.setConfig({ ...limiter.config, unfocusedMultiplier: 0.5 });
Hold the limiter to inspect config or call setConfig, which validates without
resetting counters. Runtime passes trusted identity/lifecycle observations and
retires lifecycle counters on teardown. Approval, ACL and source checks remain
independent. Without scoped permissions, hosts may explicitly install
legacyFirewall from @kehto/rate-limit/legacy; the default installs neither.
Supply RuntimeAdapter.permissions and trusted SessionEntry.permissionPrincipal
to enable shared approval for migrated service operations. Runtime exposes
permissions.grants, revoke, clear, and retryPersistence for host settings.
Persistent grants require successful durable writes; revocation failures disable
access until recovery. Services use ServiceRuntimeContext.authorizeOperation
and observe its cancellation signal. See scoped approvals
for adapter examples, lifetimes, failure handling, and the remaining migration scope.
Use runtime.permissions.admit with a trusted provisional session before starting
an app, then isAdmissionCurrent immediately before injecting the returned domains.
Required denial blocks admission; optional denial narrows the result. Built-in
interfaces require these grants. Declared service extensions use shared held
approvals, immutable bounded requests, replay protection, and independent prompt
budgets. Their onPermissionDenied hook owns any extension-specific error response.
Services may pass a request-owned signal as the fifth argument to
ServiceRuntimeContext.authorizeOperation(windowId, operation, requirements, execute, signal). Aborting it settles that request as cancelled, dismisses its
prompt through the prompt signal, and aborts the signal passed to execute.
Sibling requests keep their own lifetimes. Late approval answers cannot create
grants; late action results are discarded. The service must still observe the
execution signal before each later side effect and apply its protocol's
cancellation response rules.
A cancelled queued request settles immediately, but later equivalent requests still wait behind the active prompt. Retained queue entries count toward the queue bound until their predecessor settles. Request listeners are removed when the operation settles. An already-aborted signal never opens a prompt or invokes the action.
Registered extensions revalidate their exact capability declaration after approval and before sending deferred replies. Replacing, removing, or changing that declaration invalidates the captured operation; a late answer grants nothing.