Browser adapter over @kehto/runtime — ShellBridge and domain proxies.
ShellAdapter.permissions forwards approval UI, storage, clock, and cancellation
adapters to runtime. Supply a resolver-verified permissionPrincipal with
OriginIdentity or onNip5dIframeCreate; source registration preserves its frozen
catalog/artifact identity independently of optional shell.ready. The reference
LINK service consumes these approvals. See the approval guide
for configuration and host migration status.
admitBrowserDocument() is the shared launch transaction for verified artifacts
and explicit development targets. It registers a provisional source, obtains
runtime interface and directive-specific browser-source approval, then supplies a prepared
srcdoc with the admitted namespace and a closed default-deny CSP to one
synchronous commit callback. Hosts must retire the returned source on navigation
or closure. Direct browser origins exclude resource; revoking a launch grant
retires the frame. Browser direct traffic is not mediated or metered by the parent.
createBrowserApprovalUi() supplies a framework-free <dialog> prompt and a
grant-management view. Pass ui.prompt into ShellAdapter.permissions, call
ui.reportStorageError from the persistence error hook, and call ui.refresh()
when the runtime changes. The view always reads RuntimePermissions.grants and
uses its revoke, clear, and retryPersistence methods; it keeps no grant
store. The prompt asks a plain-language question, names the napplet with the
host's label, lists every exact scope, and preselects the narrowest offered
lifetime; the full trusted identity is one disclosure away. Network origins that
share one mediated operation, such as the relays of an outbox plan, are one
"contact N origins" row listing the exact origins (collapsed beyond openOriginLimit, default 5); each origin
is still granted on its own. Deny has initial
focus. Escape, close, and abort cancel without creating a denial grant. Grants
are grouped by napplet and interface with group revoke. Pass rules to add an
editor for host default rules and a "do this for every future request" choice
on each prompt. The UI ships unstyled: add BROWSER_APPROVAL_UI_STYLES to a
<style> element, or style the kehto-approval-* and kehto-fw-* classes.
If grant management lives in collapsible controls, pass an always-visible
promptMount such as document.body; otherwise the prompt shares mount.
ui.destroy() removes both surfaces and cancels outstanding prompts.
Alpha status: Kehto is an early runtime toolkit for a draft NIP-5D protocol. NAP contracts and injected-domain behavior are still draft; treat this package as current implementation guidance.
Browser source grants follow CSP scheme/port matching, including HTTP to HTTPS upgrades; the approval UI discloses this when relevant. Mediated network scopes continue to require exact canonical origins.
pnpm add @kehto/shell
Peers admit @napplet/core >=0.32.0 <0.46.0 and @napplet/nap
>=0.32.0 <0.46.0; the shell 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 fixture-line core 0.32.0 / nap 0.32.0 contracts follow
NAP-INTENT authority 5ac0490461ca6fec2f0d2e45b4835cf9bc08de24, napplet/web#199
source 3037200c932488f14f7f369b8583c39c9c16510a / merge
b3f0007867eac109fa4917fac9c285d3b7cc6155, and Version Packages #198 release
source dc1d24153c759152b6ba31a6ec9bea967798f2df.
@kehto/shell is the browser-specific integration layer for kehto. It wraps @kehto/runtime with the NIP-5D port-bound transport (one window-level napplet.hello, then a dedicated MessagePort), localStorage persistence hooks, an audio manager, and the five canonical per-domain proxies defined by NIP-5D.
The primary entry point is createShellBridge() — it owns the napplet.hello listener and port binding, the NAP-SHELL shell.ready / shell.init handshake, manifest verification, and every dispatch back into the runtime engine.
ACL persistence uses the browser's localStorage key napplet:acl. A failed
write is intentionally reported through bridge.runtime.aclState.persist() or
clear() as false; the runtime keeps its already-applied live state, while a
fresh bridge can still load the prior durable policy until the caller retries.
Only ACL persistence has this result contract: unrelated browser persistence
adapters retain their documented best-effort behavior.
Current draft behaviors this package enforces:
relay.publish / relay.publishEncrypted and the shell mediates the signing flow internally (NIP-44 default, NIP-04 opt-in for encrypted envelopes).AuthHooks.getSigner(windowId?) receives the originating iframe window ID
when the runtime can identify it. The shell forwards this optional context
without imposing a consent policy; host runtimes may ignore it or use it to
resolve their own identity-scoped signer decisions.prepareNappletSrcdoc() inserts validated CSP and the runtime namespace outside verified artifact bytes. It exposes only the host-selected bare domains. Optional shell installs its parent-bound receiver before readiness; routing uses trusted iframe creation identity independently of that exchange. See the living NAP-SHELL.ae5b9c64ab8a4d8909f288829a01e99d6bd713bc: bytes(url) and bytesMany(urls) carry one URL or an ordered URL array. Results use canonical padded base64 on the wire and decode to Blob values only in the injected projection.window.napplet.shell.supports(domain) answers synchronously and locally from the cached first shell.init environment. It returns false before shell.init, for unknown values, and for domains that are not live and granted to that napplet; it never sends a support-query message.createIdentityProxy, createThemeProxy, createKeysProxy, createMediaProxy, createNotifyProxy — can be composed between napplet and runtime to intercept request traffic per NAP. They are NOT wired by default. Identity/theme proxy emit() compatibility members fail closed; hosts must deliver automatic changes through ShellBridge.publishIdentityChanged() / publishTheme(), which enforce live session, granted domain, and current ACL. A napplet is a push target from its first valid napplet.hello, before it sends anything.keys.forward is napplet-to-shell only. Active napplets suppress locally-bound keys from keys.bindings before forwarding; shell-initiated action triggers use keys.action.buildShellCapabilities() advertises only live domains. Registered dm and fs services are injected only when their handlers exist; disabled domains are absent from the delivered domains and named services snapshots.The injected INC binding follows merged
naps/NAP-INC.md
on napplet/naps master
377bf939c6c906817084b43dd21d424de646dbc2. The specification remains marked
draft, but its merged path is the protocol authority.
The released package projection and window.napplet.inc binding own
query-to-text-payload
transposition: it converts a convention URI query before emitting a stable,
exact stable convention topic identity. Subscriptions reject query- or fragment-bearing
convention identities; arbitrary opaque topics remain byte-for-byte exact,
including ? and #. The binding never creates a normalized query-bearing
wire/discovery identity,
does not do prefix/wildcard/query-aware matching or service-over-INC prefix
dispatch, and does not infer payload kinds. Runtime delivery supplies the
runtime-attested endpoint identifier; no caller sender is accepted, topic source exclusion
is runtime-owned, and IDs and payloads are opaque. channel.open(target) takes that identifier (an event
sender, a channel peer, or one the host selected with bridge.runtime.getIncEndpointId(windowId)); a manifest
d tag is not a target and fails as target not found.
Merged NAP-INC and released @napplet/nap@0.32.0 both deliver one IncEvent
to on(topic, callback).
For channels, runtime ACL checks are open-only rather than per-message. The
target inc.channel.opened before the opener result creates an equivalent target
handle; channel.onOpened exposes it, while symmetric handles expose on and
onClosed. The binding retains inbound, early, and terminal lifecycle state in
order, closes on bounded overflow, and treats teardown as deterministic.
channel.list() is informational only. The downstream tracker is
kehto/web#203, with its upstream
resolution reply;
the prior opener-only interpretation is obsolete.
Kehto follows NAP-INTENT PR #106 at fc121fc264615482143eda86125863d2e1f741a2. The protected binding supports
window.napplet.intent.invoke('napplet:profile/open?pubkey=abc%2B123') and
invoke(uri, { payload, handler, handlerHint, behavior }). Query fields decode
once into text; + remains literal. An explicit payload cannot accompany an
inner query, and a #naddr recommendation cannot accompany handlerHint.
Unsupported options and caller-supplied sender data are rejected. Only a
parent-originated correlated result can settle the call.
Successful results identify retained delivery responsibility with ok,
archetype, action, convention, and an opaque handler. A target receives
one parent-attested intent.deliver, buffered by onDelivery until registration.
Acceptance is separate from later target completion.
Legacy object-form invoke(request) and open(archetype, payload?, opts?)
remain bounded compatibility adapters and warn once per iframe with
KEHTO_COMPAT_INTENT_OBJECT_INVOKE. Their removal conditions are tracked in
compatibility.
NIP-5D (nostr-protocol/nips#2303 at 51ef0cd)
binds napplet identity to a MessagePort, not the iframe Window. A Window
survives same-frame navigation, but the port lives only in the verified document:
MessageChannel before napplet scripts run,
keeps one port private, and sends the other once in a window-level
{ type: 'napplet.hello' } (NAPPLET_HELLO). Every NAP message then travels
over that port in both directions.ShellBridge.handleMessage accepts the hello only from the contentWindow of
an iframe registered in originRegistry, carrying exactly one port. It binds
the registered (dTag, aggregateHash) to the port. Shell senders use
originRegistry.postToNapplet(windowId, message) or getNappletTarget(windowId),
never iframeWindow.postMessage.load, or the port closing revokes the napplet. The
bridge closes the port, revokes its sessions, subscriptions and environment,
and calls ShellAdapter.onNappletRevoked({ windowId, reason, detail }). The
host must remove that frame. ShellBridge.revokeNapplet(windowId) revokes on
demand.ShellBridge.observeFrame(frame, windowId) watches for the second load. Call
it after the frame is in the DOM and before assigning srcdoc.load: only the replacement fires load, and browsers fire no
MessagePort close event. Lock the frame instead: put
renderNappletFramePolicyMeta() (Content-Security-Policy: frame-src 'none',
exported as NAPPLET_FRAME_POLICY) in the host page <head>, or send the
equivalent HTTP header. Browsers check every navigation of a child frame
against the embedding page's frame-src, including one the frame starts
itself, while an unfetched srcdoc still loads. hasNappletFramePolicy(document)
reports whether the meta element is present, and observeFrame warns once
when it is not. This is host page policy, not napplet protocol surface.originRegistry.register() throws for a Window that already handed over (or
lost) its port. Create a fresh iframe for every reload or navigation.ShellAdapter.onNappletMessage(windowId, message) observes each port envelope
before dispatch, for logging or readiness tracking.Napplets hosted with this prelude must not also import @napplet/shim, because
the shim sends a second hello. The retired window-level transport is recorded as
NIP5D_WINDOW_TRANSPORT_RETIRED in the compatibility register.
import { createShellBridge } from '@kehto/shell';
import { createNotificationService } from '@kehto/services';
const bridge = createShellBridge({
adapter: myShellAdapter,
hooks: myHooks,
target: window,
});
// Register a reference service against the underlying runtime.
bridge.runtime.registerService(
'notify',
createNotificationService({ onChange: updateBadge }),
);
Services added to the adapter after createShellBridge() are advertised only
once they are also registered with bridge.runtime.registerService(); until
then the shell leaves them out and logs [KEHTO_SERVICE_NOT_REGISTERED] once.
createShellBridge — primary entry point; returns a ShellBridge (exposed runtime, shell.ready, lifecycle hooks, observeFrame, revokeNapplet)NAPPLET_HELLO — the NIP-5D port handoff message typeShellBridge — interface type for the returned bridgerandomUUID — secure UUID v4 for host identifiers; falls back to crypto.getRandomValues() where the browser omits crypto.randomUUID() and throws when neither existsadaptHooks — convert a ShellAdapter + BrowserDeps into the canonical RuntimeAdapter hook bag consumed by @kehto/runtimeShellAdapter.aclDefaultPolicy? — 'permissive' | 'restrictive', forwarded to the runtime. See the @kehto/runtime docs for how it treats persisted ACL state.ShellAdapter.permissions forwards scoped approvals and optional rateLimiter
and promptRateLimiter instances without constructing defaults. Hold each
@kehto/rate-limit instance to update its config through setConfig.
getFocusContext supplies trusted focus to installed controls. Hosts without
permissions can explicitly pass legacyFirewall from @kehto/rate-limit/legacy
and audit it through onFirewallEvent. The legacy adapter owns its config storage.
ShellAdapter.onNappletRevoked?(revocation) — called once when the bridge revokes a NIP-5D binding (NappletRevocation: { windowId, reason, detail }, reason one of NappletRevocationReason). The host must remove the frame.ShellAdapter.onNappletMessage?(windowId, message) — observe-only; called for each NAP envelope received on a bound port before dispatch.ShellAdapter.filterNappletMessage?(windowId, message) — returns 'dispatch', 'drop' or 'defer' (NappletMessageDecision) for each NAP envelope on a bound port, before the runtime sees it. A filter that throws or returns anything else drops the envelope. shell.ready skips the filter, because NAP-SHELL requires its first shell.init reply. A dropped request gets no reply.ShellBridge.releaseDeferred(windowId) — dispatches a window's deferred envelopes in arrival order and returns how many went through. ACL checks, firewall approvals and budgets run at release, so a held request can prompt or be refused then, and a source retired meanwhile runs nothing. While envelopes are deferred, later ones can't overtake them. A window holding more than MAX_DEFERRED_MESSAGES (1024) is revoked with deferred-overflow, and revoking discards whatever was held.ShellAdapter.onUnroutedMessage?(info) — optional observe-only hook fired when ShellBridge.handleMessage drops an incoming postMessage it can't route to a registered napplet window. info is an UnroutedMessageInfo ({ type?, origin, reason }) where reason is 'no-source-window' or 'unregistered-window'. The message is still dropped — this exists so otherwise-silent drops (e.g. an intent/srcdoc iframe whose contentWindow was never registered in originRegistry, or was swapped by a reload) are diagnosable instead of vanishing. Host can console.warn inside its own hook; the bridge adds no console output and swallows hook errors so routing is never broken.const bridge = createShellBridge({
...myShellAdapter,
onUnroutedMessage: ({ type, origin, reason }) => {
console.warn(`[shell] dropped ${type ?? '<unknown>'} from ${origin}: ${reason}`);
},
});
prepareNappletSrcdoc — recommended verified-document entry point; applies CSP and namespace togetherbuildNappletCsp, renderNappletCspMeta, injectNappletCsp — shared policy construction and CSP-only composition utilitiesbuildShellCapabilities — construct the immutable domain-only ShellCapabilities payload emitted during the shell.ready / shell.init handshakeresolveShellEnvironment(hooks, identity) — host-integrator-only utility that narrows the live environment for a trusted creation-time identity before shell.init; it is not installed on window.napplet and is not a shim-facing napplet APIinjectNappletNamespacePrelude — low-level bootstrap-only insertion for development wrappers; does not apply CSPrenderNappletNamespacePrelude — render only the bootstrap <script> for hosts that already own HTML insertionResolve and verify the signed manifest, aggregate and artifact bytes before
calling prepareNappletSrcdoc. Keep the verified bytes for identity and caching;
only the rendered copy receives policy and bootstrap. Bind the iframe window to
the verified identity before assigning srcdoc, with sandbox="allow-scripts".
import { prepareNappletSrcdoc } from '@kehto/shell';
const srcdoc = prepareNappletSrcdoc(verifiedHtml, {
domains: ['theme'],
csp: {
connectOrigins: ['https://api.example'],
directives: { 'media-src': ['blob:'], 'img-src': ['data:'] },
},
});
Omitting csp applies NIP-5D's conservative baseline, including WASM compilation.
Directive overrides replace individual source lists. They cannot disable CSP
insertion, allow 'unsafe-eval', or suppress the inline namespace bootstrap.
connect-src defaults to the exact connectOrigins grants and can be narrowed;
wildcards, scheme-wide grants, credentials, paths, query strings and fragments
are rejected. Empty source lists are rejected; use ["'none'"] to deny a
directive. Hosts may remove WASM permission by setting
'script-src': ["'unsafe-inline'"].
script-src and an explicit script-src-elem must permit the inline bootstrap.
Nonce/hash/strict-dynamic combinations that suppress that allowance are rejected;
nonce-based bootstrap authorization is not supported by this API. Existing
artifact CSP and inherited response policies still apply cumulatively and may
block execution; this helper never strips them to make a napplet run.
Meta-unsupported directives (frame-ancestors, sandbox, report-uri) and
unsupported directive names are rejected. Configure embedding restrictions on
the host HTTP response. See the CSP enforcement contract
for normative requirements, enforced recommendations and configurable defaults.
createIdentityProxy — intercept identity read requests; direct emit() is prohibitedcreateThemeProxy — intercept theme.get; direct emit() is prohibitedcreateKeysProxy — intercept keys.bind/unbind/bindingscreateMediaProxy — intercept media.* playback controlThe injected identity/theme bindings follow NAP-IDENTITY and NAP-THEME at
napplet/naps master 5ac0490461ca6fec2f0d2e45b4835cf9bc08de24.
They are readonly protected objects: identity exposes supported reads and
onChanged, while theme exposes get and onChanged only. Results and
automatic changes are accepted only when their MessageEvent.source is
window.parent; direct-domain and whole-namespace assignment cannot replace
the canonical operations.
ShellBridge delivers identity.changed and theme.changed exactly once per
eligible recipient: a live authenticated source-bound session, its frozen
environment includes the relevant domain, and its current recipient read
capability is still granted. Identity sign-out is pubkey: "". Theme updates
arrive only after the service has stored the complete color state. These are
automatic change messages, not NAP-INC/intent delivery and not a subscription
protocol. Kehto's denied/unavailable theme read policy is a complete fixed
normal result without error, deliberately avoiding a mixed theme/error
payload.
createNotifyProxy — intercept notify.send/list/read/dismisssessionRegistry — canonical windowId ↔ verified-napplet registry singletonnappKeyRegistry — deprecated alias for sessionRegistryoriginRegistry — iframe Window → windowId/identity map; also holds each window's bound NIP-5D port (bindPort, getPort, postToNapplet, getNappletTarget, isSpent)NappletMessageTarget — port-backed outbound target passed to RelayPoolHooks.openScopedRelayPendingUpdate — type for pending aggregate-hash change promptsEnvironment snapshots belong to one source registration. To retire a window,
call bridge.runtime.destroyWindow(windowId),
bridge.runtime.sessionRegistry.unregister(windowId), and
originRegistry.unregister(windowId). When registering a replacement under the
same window ID (always a fresh iframe — a spent Window cannot be re-registered), provide its snapshot with originRegistry.setEnvironment() or
let the bridge call resolveShellEnvironment() for current host defaults. A
retired registration's cached domains and service names are discarded even when
the runtime session was already removed. This applies before any domain dispatch,
including requests sent before the optional shell.ready exchange.
manifestCache — browser-specific manifest cache singletonManifestCacheEntry — manifest cache entry typeaudioManager — browser audio registry singleton (audio element pool)AudioSource — per-windowId audio source shapeTOPICS — canonical shell topic namespace for command routingTopicKey, TopicValue — typed topic lookup helpersExported for host-app integration: ShellAdapter, ShellCapabilities, CapabilityHooks, OriginIdentity, RelayPoolHooks, RelayPoolLike, RelayConfigHooks, WindowManagerHooks, AuthHooks, ConfigHooks, HotkeyHooks, WorkerRelayHooks, WorkerRelayLike, CryptoHooks, DmHooks, UploadHooks, IntentHooks, LinkHooks, CommonHooks, ListsHooks, SerialHooks, BleHooks, WebrtcHooks, SessionEntry, NappKeyEntry (deprecated), AclEntry, AclCheckEvent, FirewallEvent, FirewallPersistence, UnroutedMessageInfo, ServiceDescriptor, ServiceHandler, ServiceRegistry, NostrEvent, NostrFilter, NappletMessage, ConsentRequest, and per-proxy *Deps/*Proxy interfaces.
RelayPoolLike.publish() may return Promise<void> when transport acceptance
is asynchronous. The shell adapter forwards that promise so the runtime does
not acknowledge or buffer an event before the relay operation settles.
RelayPoolHooks.publishToScopedRelay() may likewise return
Promise<boolean> so asynchronous hosts report the settled outcome.
createEnforceGate, createNapEnforceGate, formatDenialReason, plus EnforceResult, EnforceConfig, NapEnforceConfig, IdentityResolver, AclChecker, NapMessage.
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 from @kehto/runtime: the v1.1 bus-kind enum, auth event kind, shell bridge URI constant, protocol version string, the full capability list, destructive-kind set, and the replay window seconds constant. Re-exported types cover the v1.1 capability union and bus-kind numeric union. See the typedoc API reference below for the exact identifier list.
Full package docs: docs/packages/shell.md.
Generated API module: docs/api/modules/_kehto_shell.html (run pnpm docs:api).
MIT
Current manifests use a direct artifact x hash, plain-text content, role-matched
z/i intent declarations, and required R / optional O domains. Kehto also
accepts legacy aggregate events through an isolated compatibility adapter.
Existing aggregateHash host/cache/ACL fields carry the verified artifact hash
for current events; legacy identities keep their original aggregate. Both paths
verify signatures and bytes before runtime injection and srcdoc execution.
For the schema and removal boundary, see event migration.
The injected window.napplet.intent.onDelivery(handler) returns a closeable
subscription and drains buffered parent deliveries in order. Register it to
receive { sender, archetype, action, convention, payload? }; INC is not required.
Its receiver is installed before shell.ready and survives namespace reassignment.
A throwing listener does not prevent delivery to other listeners.
When no canonical listener is registered, matching legacy INC listeners can
consume the delivery locally. This emits KEHTO_COMPAT_INTENT_INC once per
iframe; a delivery is never replayed to both APIs. See compatibility tracking.
Delivery and URI invocation follow NAP-INTENT PR #106 at
fc121fc264615482143eda86125863d2e1f741a2; the packaged SDK still trails that
contract, as documented in the conformance policy.
The shell normalizer also powers Paja intent links. See the Paja guide for outer URL encoding, review, routing, and verified launcher behavior.
A verified napplet is an about:srcdoc document and inherits the host page's
referrer and base URL. Keep the shell URL out of it with
denyNappletReferrer(frame) before assigning srcdoc, plus
renderNappletReferrerPolicyMeta() and renderNappletHostBase() in the host
page <head> (WebKit ignores the iframe attribute for srcdoc; only a host-page
<base> reaches document.baseURI). hasNappletReferrerPolicy(frame) and
hasNappletReferrerPolicyMeta(document) report the two controls, and
ShellBridge.observeFrame warns once when either is missing.
The experimental namespace adds resourceHintLock next to nestedContextLock.
It rejects <link rel="dns-prefetch" | "preconnect" | "prerender">, which
browsers act on outside the napplet CSP, on every string sink and attribute
writer; scan the bytes first with assertNappletHasNoResourceHint (or
nappletMarkupHasResourceHint). Both locks remove XSLTProcessor, reject
namespace-prefixed frame and link tags, and inspect DOMParser results, which
otherwise mint frames past the nested-context lock through XSLT or XML parsing
(prefixes, DTD entities). Under the nested-context
lock the bridge revokes a napplet whose Window holds a child frame
(nested-context); hosts that prepare the srcdoc themselves opt in with
observeFrame(frame, windowId, { nestedContextLock: true })
(NappletFrameObservation). See the
NIP-5D conformance policy.
This non-normative guidance defers to the living NAP-GAMEPAD. Services export createGamepadService and browserGamepadOptions; shell exports denyNappletControllerAccess. Paja registers one host reader and deny 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.
Host identifiers that must be unguessable come from randomUUID, exported by
@kehto/shell. It calls native crypto.randomUUID() on its Crypto receiver
when available. On browsers that omit it (including non-localhost plain HTTP
origins), it builds a UUID v4 from 16 crypto.getRandomValues() bytes. If both
methods are unavailable it throws an explicit capability error; it never falls
back to weak randomness. @kehto/services has no dependency on the shell, so
it keeps a private twin of the same function; tests/unit/random-uuid-sync.test.ts
fails when the two bodies drift.
Each identifier has one of three contracts:
| Contract | Identifiers | Without crypto.randomUUID |
|---|---|---|
| Secure, fails explicitly | Shell event-injection subscription ids, cache-query ids, and the RuntimeAdapter crypto.randomUUID hook (injected event ids, relay query ids, NAP-INC channel ids, approval request ids); source-session instanceId in the shell and in Paja frame admission; Paja intent-launcher window ids and launch correlations; Paja NIP-46 request ids; default upload ids (createUploadService); the browser media backend's media-resource-* read ids, which share a window's resource-request id space with the napplet; registry JSON-RPC ids in createCvmService |
UUID v4 from crypto.getRandomValues(), or a thrown capability error when that is missing too |
| Correlation only, uniqueness from a counter or timestamp | Injected napplet-namespace request ids (the napplet realm pairing its own requests on its private port); default LLM connection handles and synthesized tool-call ids (window- and conversation-scoped); notification ids; Paja filesystem mount ids and LLM panel connection ids | Feature-detected; a counter or timestamp keeps ids unique. These ids are never credentials |
Behind crypto.subtle |
Paja WebRTC session, nonce, and peer ids (browser-webrtc.ts, browser-webrtc-profile.ts) |
Unavailable. Both paths need crypto.subtle before they mint an id, and every browser context that has crypto.subtle also has crypto.randomUUID |
A UUID fallback does not provide secure-context APIs. crypto.subtle stays
unavailable on non-localhost HTTP, so SHA-256 digest paths still fail there:
approval-scoped uploads and the default createHttpUploader digest, CVM
schema-hash verification and progress tokens, Paja development-target and
filesystem hashing, and the Paja LLM vault. This section does not establish
HTTP support for uploads, CVM, or any other domain.
This is a supported platform capability choice, not a deprecated caller API.
Both standard Web Crypto paths remain quiet. Identifier generation is host
implementation policy: no NAP wire message, source-trust rule, or readiness
rule changes. Source-bound identity and optional shell readiness are unchanged
(NAP-SHELL at napplet/naps 377bf939c6c906817084b43dd21d424de646dbc2).