@kehto/runtime 0.2.0 → 0.5.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 CHANGED
@@ -2,6 +2,10 @@
2
2
 
3
3
  Browser-agnostic protocol engine for the napplet protocol.
4
4
 
5
+ > **Alpha status:** Kehto is an early runtime implementation for a draft NIP-5D
6
+ > protocol. NUB contracts and runtime APIs are not final; treat this package as
7
+ > current implementation guidance, not as a stable protocol guarantee.
8
+
5
9
  ## Install
6
10
 
7
11
  ```bash
@@ -10,9 +14,9 @@ pnpm add @kehto/runtime
10
14
 
11
15
  ## Overview
12
16
 
13
- `@kehto/runtime` is the canonical v1.2 NIP-5D protocol engine. It owns every incoming napplet message, gates it through the ACL enforcement layer, routes it to the correct NUB handler, and emits the corresponding reply envelope.
17
+ `@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 NUB handler, and emits the corresponding reply envelope.
14
18
 
15
- The runtime is built around the canonical dispatch contract from `@napplet/core` — `createDispatch()` + `registerNub()` — so routing is declarative, not a hand-rolled switch. Covers all eight canonical NIP-5D domains end-to-end:
19
+ The runtime is built around the current draft dispatch contract from `@napplet/core` — `createDispatch()` + `registerNub()` — so routing is declarative, not a hand-rolled switch. It covers the NIP-5D domains currently supported by Kehto:
16
20
 
17
21
  - **identity** — `identity.getProfile`, `identity.getFollows`, `identity.getPublicKey`, …
18
22
  - **ifc** — `ifc.channel.*`, `ifc.emit`, cross-napplet pub/sub
@@ -40,7 +44,7 @@ const runtime = createRuntime({
40
44
  // ... further adapter hooks
41
45
  });
42
46
 
43
- // Incoming canonical v1.2 envelope from a napplet:
47
+ // Incoming NIP-5D draft envelope from a napplet:
44
48
  runtime.handleMessage('window-1', {
45
49
  type: 'relay.publish',
46
50
  id: 'evt-42',
@@ -51,52 +55,53 @@ runtime.handleMessage('window-1', {
51
55
  ## Public API
52
56
 
53
57
  ### Runtime factory
54
- - [`createRuntime`](../../docs/api/functions/_kehto_runtime.createRuntime.html) — primary entry point; `Runtime` interface type
58
+ - `createRuntime` — primary entry point; `Runtime` interface type
55
59
 
56
60
  ### Enforcement gate
57
- - [`createEnforceGate`](../../docs/api/functions/_kehto_runtime.createEnforceGate.html) — legacy pubkey-keyed ACL gate
58
- - [`createNubEnforceGate`](../../docs/api/functions/_kehto_runtime.createNubEnforceGate.html) — NIP-5D windowId-keyed ACL gate
59
- - [`resolveCapabilitiesNub`](../../docs/api/functions/_kehto_runtime.resolveCapabilitiesNub.html) — map a NIP-5D envelope to required capabilities (re-exported from `@kehto/acl`)
60
- - [`formatDenialReason`](../../docs/api/functions/_kehto_runtime.formatDenialReason.html) — `denied: <capability>` canonical string
61
+ - `createEnforceGate` — legacy pubkey-keyed ACL gate
62
+ - `createNubEnforceGate` — NIP-5D windowId-keyed ACL gate
63
+ - `resolveCapabilitiesNub` — map a NIP-5D envelope to required capabilities (re-exported from `@kehto/acl`)
64
+ - `formatDenialReason` — `denied: <capability>` canonical string
61
65
 
62
66
  ### Session registry
63
- - [`createSessionRegistry`](../../docs/api/functions/_kehto_runtime.createSessionRegistry.html) — bidirectional windowId ↔ `SessionEntry` store
67
+ - `createSessionRegistry` — bidirectional windowId ↔ `SessionEntry` store
64
68
  - `createNappKeyRegistry` — deprecated alias retained for v1.1 migration consumers
65
69
 
66
70
  ### ACL state container
67
- - [`createAclState`](../../docs/api/functions/_kehto_runtime.createAclState.html) — persistence-backed wrapper around `@kehto/acl` state
71
+ - `createAclState` — persistence-backed wrapper around `@kehto/acl` state
68
72
 
69
73
  ### Manifest cache
70
- - [`createManifestCache`](../../docs/api/functions/_kehto_runtime.createManifestCache.html) — NIP-5A aggregate-hash cache with persistence hooks
74
+ - `createManifestCache` — NIP-5A aggregate-hash cache with persistence hooks
71
75
 
72
76
  ### Replay detection
73
- - [`createReplayDetector`](../../docs/api/functions/_kehto_runtime.createReplayDetector.html) — duplicate-event + timestamp-window guard
77
+ - `createReplayDetector` — duplicate-event + timestamp-window guard
74
78
 
75
79
  ### Event buffer
76
- - [`createEventBuffer`](../../docs/api/functions/_kehto_runtime.createEventBuffer.html) — ring buffer with subscription delivery
77
- - [`matchesFilter`](../../docs/api/functions/_kehto_runtime.matchesFilter.html), [`matchesAnyFilter`](../../docs/api/functions/_kehto_runtime.matchesAnyFilter.html) — pure NIP-01 filter helpers
80
+ - `createEventBuffer` — ring buffer with subscription delivery
81
+ - `matchesFilter`, `matchesAnyFilter` — pure NIP-01 filter helpers
78
82
  - `RING_BUFFER_SIZE` — default ring buffer capacity constant
79
83
 
80
84
  ### State handler
81
- - [`handleStorageNub`](../../docs/api/functions/_kehto_runtime.handleStorageNub.html) — canonical `storage.*` NIP-5D handler
82
- - [`cleanupNappState`](../../docs/api/functions/_kehto_runtime.cleanupNappState.html) — remove persisted state when a napplet window closes
85
+ - `handleStorageNub` — canonical `storage.*` NIP-5D handler
86
+ - `cleanupNappState` — remove persisted state when a napplet window closes
83
87
 
84
88
  ### Service dispatch
85
- - [`routeServiceMessage`](../../docs/api/functions/_kehto_runtime.routeServiceMessage.html) — domain-prefix router into the service registry
86
- - [`notifyServiceWindowDestroyed`](../../docs/api/functions/_kehto_runtime.notifyServiceWindowDestroyed.html) — lifecycle fan-out to every service handler
89
+ - `routeServiceMessage` — domain-prefix router into the service registry
90
+ - `notifyServiceWindowDestroyed` — lifecycle fan-out to every service handler
87
91
 
88
92
  ### Types
89
93
  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.
90
94
 
91
95
  ### Compat re-exports (DRIFT-CORE-06)
92
96
 
93
- Retained for v1.1 migration consumers; new integrations should use canonical NIP-5D envelope types from `@napplet/core`. Slated for removal once upstream restores those exports.
97
+ Retained for migration consumers; new integrations should use current NIP-5D envelope types from `@napplet/core`. Slated for removal once upstream restores those exports.
94
98
 
95
99
  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.
96
100
 
97
101
  ## API Reference
98
102
 
99
- Full API reference: [docs/api/@kehto/runtime/](../../docs/api/modules/_kehto_runtime.html) (generated via `pnpm docs:api`).
103
+ Full package docs: [`docs/packages/runtime.md`](../../docs/packages/runtime.md).
104
+ Generated API module: `docs/api/modules/_kehto_runtime.html` (run `pnpm docs:api`).
100
105
 
101
106
  ## License
102
107
 
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { NappletMessage, NostrEvent, NostrFilter } from '@napplet/core';
1
+ import { NappletMessage, NostrEvent, EventTemplate, NostrFilter } from '@napplet/core';
2
2
  export { NappletMessage } from '@napplet/core';
3
3
  import { Capability } from '@kehto/acl/capabilities';
4
4
  export { ALL_CAPABILITIES, Capability } from '@kehto/acl/capabilities';
@@ -12,6 +12,13 @@ export { NubMessage, resolveCapabilitiesNub } from '@kehto/acl';
12
12
  * to host napplets. No DOM types, no browser APIs.
13
13
  */
14
14
 
15
+ /**
16
+ * A napplet class identifier. `null` is the permissive default (no class).
17
+ * provisional — mirrors packages/shell/src/types/internal-class.ts::NappletClass;
18
+ * converges on @napplet/nub/class@^0.3.0 publish. Runtime MUST NOT import
19
+ * from shell (module-boundary), so this duplicate lives here.
20
+ */
21
+ type NappletClass = string | null;
15
22
  /**
16
23
  * Event emitted on every ACL enforcement check.
17
24
  *
@@ -39,11 +46,19 @@ interface AclCheckEvent {
39
46
  decision: 'allow' | 'deny';
40
47
  /** The triggering message, if available. Accepts NIP-01 arrays or NIP-5D NappletMessage envelopes. */
41
48
  message?: unknown[] | NappletMessage;
49
+ /**
50
+ * Why the decision was reached (v1.7 CLASS-03 / D7). Optional for
51
+ * backwards compatibility with pre-v1.7 audit consumers.
52
+ * 'allowed' -> decision === 'allow'
53
+ * 'capability-missing' -> decision === 'deny' (capability lookup failed)
54
+ * 'class-forbidden' -> decision === 'deny' (class pre-filter refused)
55
+ */
56
+ reason?: 'allowed' | 'capability-missing' | 'class-forbidden';
42
57
  }
43
58
  /**
44
59
  * Abstract message sender — the runtime calls this to send messages
45
60
  * back to a specific napplet. The transport layer (postMessage, WebSocket,
46
- * IPC channel, etc.) is the implementor's concern.
61
+ * host bridge channel, etc.) is the implementor's concern.
47
62
  *
48
63
  * Accepts both NIP-01 array format (legacy) and NIP-5D NappletMessage envelope format.
49
64
  *
@@ -95,7 +110,7 @@ interface CacheAdapter {
95
110
  /** NIP-07 compatible signer interface — minimal methods the runtime needs. */
96
111
  interface Signer {
97
112
  getPublicKey?(): string | Promise<string>;
98
- signEvent?(event: NostrEvent): Promise<NostrEvent>;
113
+ signEvent?(event: NostrEvent | EventTemplate): Promise<NostrEvent>;
99
114
  getRelays?(): Record<string, {
100
115
  read: boolean;
101
116
  write: boolean;
@@ -375,11 +390,18 @@ interface SessionEntry {
375
390
  /** Persistent GUID for this iframe instance, assigned by the runtime. Survives page reloads. */
376
391
  instanceId: string;
377
392
  /**
378
- * How session identity was established.
379
- * 'source' = NIP-5D (identity registered at iframe creation via originRegistry).
380
- * 'auth' = legacy AUTH handshake (pubkey is the derived keypair pubkey).
393
+ * How session identity was established (RENAME-01, v1.8 Phase 42).
394
+ * 'nip-5d' = identity registered at iframe creation via originRegistry (canonical NIP-5D path).
395
+ * 'legacy-auth' = legacy AUTH handshake (pubkey is the derived keypair pubkey).
396
+ * Renamed from `identitySource: 'auth' | 'source'` in v1.8; see .changeset/v1-8-rename-01-session-provenance.md.
381
397
  */
382
- identitySource: 'auth' | 'source';
398
+ provenance: 'nip-5d' | 'legacy-auth';
399
+ /**
400
+ * Class posture resolved synchronously at iframe creation (CLASS-02).
401
+ * `null` is the permissive default (D2). Class tokens like 'class-1' /
402
+ * 'class-2' are NUB-defined. See packages/shell/src/types/internal-class.ts.
403
+ */
404
+ class: NappletClass;
383
405
  }
384
406
  /** @deprecated Use SessionEntry. Will be removed in v0.9.0. */
385
407
  type NappKeyEntry = SessionEntry;
@@ -505,7 +527,7 @@ interface RuntimeConfigOverrides {
505
527
  *
506
528
  * This is the primary integration point. A browser shell implements these
507
529
  * by wrapping postMessage, localStorage, and relay pool libraries.
508
- * A CLI or server shell could implement them with IPC channels, file
530
+ * A CLI or server shell could implement them with host bridge channels, file
509
531
  * storage, and direct WebSocket connections.
510
532
  *
511
533
  * @example
@@ -626,26 +648,22 @@ interface RuntimeAdapter {
626
648
  getConfigOverrides?(): RuntimeConfigOverrides;
627
649
  }
628
650
 
629
- /**
630
- * enforce.ts — Single ACL enforcement gate for the NIP-5D runtime.
631
- *
632
- * All NIP-5D NappletMessage envelopes pass through createNubEnforceGate()
633
- * before any handler acts. resolveCapabilitiesNub() (re-exported from
634
- * @kehto/acl) maps NUB message types to required capabilities. No NIP-01
635
- * dispatch path remains — v1.4 Phase 24 DRIFT-02 deleted the legacy
636
- * capability-resolution function along with its dead kind + topic
637
- * dispatch table.
638
- */
639
-
640
651
  /**
641
652
  * Result of an enforcement check.
642
653
  *
643
654
  * @param allowed - Whether the capability check passed
644
655
  * @param capability - The capability that was checked (human-readable string)
656
+ * @param reason - Why the decision was reached (v1.7 CLASS-03 / D7). Always set on return.
645
657
  */
646
658
  interface EnforceResult {
647
659
  allowed: boolean;
648
660
  capability: Capability;
661
+ /**
662
+ * Why the decision was reached (v1.7 CLASS-03 / D7). Always set on the
663
+ * return path. Distinct from AclCheckEvent.reason (which is optional for
664
+ * backwards compat on the audit surface).
665
+ */
666
+ reason: 'allowed' | 'capability-missing' | 'class-forbidden';
649
667
  }
650
668
  /**
651
669
  * Identity lookup function type — resolves a pubkey to its full identity.
@@ -699,7 +717,9 @@ declare function createEnforceGate(config: EnforceConfig): (pubkey: string, capa
699
717
  * Uses windowId for identity resolution instead of pubkey (which is '' in NIP-5D sessions).
700
718
  *
701
719
  * @param checkAcl - The ACL check function
702
- * @param resolveIdentityByWindowId - Maps windowId to identity (dTag, aggregateHash)
720
+ * @param resolveIdentityByWindowId - Maps windowId to identity (dTag, aggregateHash, class). Returns
721
+ * class posture inline (v1.7 CLASS-03) so the NUB gate can pre-filter class-forbidden capabilities
722
+ * before consulting the ACL check. null class = permissive default (D2).
703
723
  * @param onAclCheck - Optional audit callback, called on every enforceNub() check
704
724
  */
705
725
  interface NubEnforceConfig {
@@ -707,6 +727,7 @@ interface NubEnforceConfig {
707
727
  resolveIdentityByWindowId: (windowId: string) => {
708
728
  dTag: string;
709
729
  aggregateHash: string;
730
+ class: NappletClass;
710
731
  } | undefined;
711
732
  onAclCheck?: (event: AclCheckEvent) => void;
712
733
  }
@@ -745,16 +766,6 @@ declare function createNubEnforceGate(config: NubEnforceConfig): (windowId: stri
745
766
  */
746
767
  declare function formatDenialReason(capability: Capability): string;
747
768
 
748
- /**
749
- * SessionRegistry — windowId to verified napplet pubkey bidirectional mapping.
750
- *
751
- * After a successful AUTH handshake, the runtime registers the napplet's
752
- * verified pubkey here. Both mappings are kept in sync.
753
- *
754
- * Unlike the shell singleton version, this is a factory that accepts
755
- * an optional notifier callback instead of using window.dispatchEvent.
756
- */
757
-
758
769
  /**
759
770
  * Bidirectional registry mapping windowIds to verified napplet pubkeys.
760
771
  * Maintained by the runtime after successful AUTH handshakes.
@@ -1058,17 +1069,6 @@ interface EventBuffer {
1058
1069
  */
1059
1070
  declare function createEventBuffer(sendToNapplet: SendToNapplet, sessionRegistry: SessionRegistry, enforce: (pubkey: string, capability: Capability, message?: unknown[]) => EnforceResult, subscriptions: Map<string, SubscriptionEntry>, getBufferSize?: () => number): EventBuffer;
1060
1071
 
1061
- /**
1062
- * runtime.ts — The napplet protocol engine factory.
1063
- *
1064
- * createRuntime(hooks) creates the complete protocol engine that handles
1065
- * NIP-5D NUB domain dispatch, ACL enforcement, subscription lifecycle,
1066
- * signer proxying, and shell command routing.
1067
- *
1068
- * No browser APIs. No DOM. No localStorage. No postMessage.
1069
- * All I/O is delegated to RuntimeAdapter.
1070
- */
1071
-
1072
1072
  /**
1073
1073
  * The napplet protocol engine — handles NIP-5D NUB domain dispatch,
1074
1074
  * ACL enforcement, subscription lifecycle.
@@ -1149,25 +1149,25 @@ declare function createRuntime(hooks: RuntimeAdapter): Runtime;
1149
1149
  * state-handler.ts — Storage NUB request handler using persistence hooks.
1150
1150
  *
1151
1151
  * Handles napplet storage operations (get, set, remove, keys) via the
1152
- * canonical `@napplet/nub-storage` NIP-5D envelope surface. Delegates
1152
+ * canonical `@napplet/nub/storage` NIP-5D envelope surface. Delegates
1153
1153
  * storage to StatePersistence. No localStorage, no legacy NIP-01 dispatch.
1154
1154
  */
1155
1155
 
1156
1156
  /**
1157
1157
  * Handle a NIP-5D NUB storage message from a napplet.
1158
- * Routes to the canonical four `@napplet/nub-storage` actions:
1158
+ * Routes to the canonical four `@napplet/nub/storage` actions:
1159
1159
  * - `storage.get` → `storage.get.result` `{ value: string | null }`
1160
1160
  * - `storage.set` → `storage.set.result` `{ ok: boolean }` (canonical only checks `error`)
1161
1161
  * - `storage.remove` → `storage.remove.result` `{ ok: boolean }`
1162
1162
  * - `storage.keys` → `storage.keys.result` `{ keys: string[] }`
1163
1163
  *
1164
- * `storage.clear` is NOT in the canonical `@napplet/nub-storage` union (it was a
1165
- * kehto unilateral extension); it now produces a `storage.clear.error` envelope.
1166
- * Internal lifecycle cleanup still uses the `cleanupNappState()` helper below —
1167
- * it is not napplet-reachable.
1164
+ * `storage.clear` is NOT in the canonical `@napplet/nub/storage` union (it was a
1165
+ * kehto unilateral extension); attempts produce a `storage.clear.result` envelope
1166
+ * with an `error` field set. Internal lifecycle cleanup still uses the
1167
+ * `cleanupNappState()` helper below — it is not napplet-reachable.
1168
1168
  *
1169
1169
  * **Deviation note (Phase 15 to decide):** Set/remove results emit both `ok`
1170
- * (legacy compat) and an `error` field on failure. Canonical `@napplet/nub-storage`
1170
+ * (legacy compat) and an `error` field on failure. Canonical `@napplet/nub/storage`
1171
1171
  * only specifies the optional `error`; napplets check `!result.error` for success.
1172
1172
  * Emitting `ok` preserves backward compatibility with existing in-tree callers.
1173
1173
  * Phase 15 (v1.2 release prep) decides whether to drop `ok` pre-release.
@@ -1207,15 +1207,6 @@ declare function handleStorageNub(windowId: string, msg: NappletMessage, sendToN
1207
1207
  */
1208
1208
  declare function cleanupNappState(pubkey: string, dTag: string, aggregateHash: string, statePersistence: StatePersistence): void;
1209
1209
 
1210
- /**
1211
- * service-dispatch.ts — NIP-5D envelope routing for registered services.
1212
- *
1213
- * Routes NappletMessage envelopes to the correct ServiceHandler based on the
1214
- * message type domain prefix. NUB-domain services (signer.*, relay.*, storage.*)
1215
- * are routed by the domain part of message.type. IFC-routed services (audio,
1216
- * notifications) receive ifc.emit messages and are routed by topic prefix.
1217
- */
1218
-
1219
1210
  /**
1220
1211
  * Route a NappletMessage envelope to the matching service handler.
1221
1212
  *
@@ -1256,4 +1247,4 @@ declare function routeServiceMessage(windowId: string, message: NappletMessage,
1256
1247
  */
1257
1248
  declare function notifyServiceWindowDestroyed(windowId: string, services: ServiceRegistry): void;
1258
1249
 
1259
- export { type AclCheckEvent, type AclChecker, type AclEntryExternal, type AclPersistence, type AclStateContainer, type AuthAdapter, type CacheAdapter, type CompatibilityReport, type ConfigAdapter, type ConsentHandler, type ConsentRequest, type CryptoAdapter, type DmAdapter, type EnforceConfig, type EnforceResult, type EventBuffer, type GuidPersistence, type HashVerifierAdapter, type HotkeyAdapter, type IdentityResolver, type ManifestCache, type ManifestCacheEntry, type ManifestPersistence, type NappKeyEntry, type NappKeyRegistry, type NubEnforceConfig, type PendingUpdate, type PendingUpdateNotifier, RING_BUFFER_SIZE, type RelayConfigAdapter, type RelayPoolAdapter, type RelaySubscriptionHandle, type ReplayDetector, type Runtime, type RuntimeAdapter, type RuntimeConfigOverrides, type SendToNapplet, type ServiceDescriptor, type ServiceHandler, type ServiceInfo, type ServiceRegistry, type SessionEntry, type SessionRegistry, type ShellSecretPersistence, type Signer, type StatePersistence, type SubscriptionEntry, type VerificationCacheEntry, type WindowManagerAdapter, cleanupNappState, createAclState, createEnforceGate, createEventBuffer, createManifestCache, createNappKeyRegistry, createNubEnforceGate, createReplayDetector, createRuntime, createSessionRegistry, formatDenialReason, handleStorageNub, matchesAnyFilter, matchesFilter, notifyServiceWindowDestroyed, routeServiceMessage };
1250
+ export { type AclCheckEvent, type AclChecker, type AclEntryExternal, type AclPersistence, type AclStateContainer, type AuthAdapter, type CacheAdapter, type CompatibilityReport, type ConfigAdapter, type ConsentHandler, type ConsentRequest, type CryptoAdapter, type DmAdapter, type EnforceConfig, type EnforceResult, type EventBuffer, type GuidPersistence, type HashVerifierAdapter, type HotkeyAdapter, type IdentityResolver, type ManifestCache, type ManifestCacheEntry, type ManifestPersistence, type NappKeyEntry, type NappKeyRegistry, type NappletClass, type NubEnforceConfig, type PendingUpdate, type PendingUpdateNotifier, RING_BUFFER_SIZE, type RelayConfigAdapter, type RelayPoolAdapter, type RelaySubscriptionHandle, type ReplayDetector, type Runtime, type RuntimeAdapter, type RuntimeConfigOverrides, type SendToNapplet, type ServiceDescriptor, type ServiceHandler, type ServiceInfo, type ServiceRegistry, type SessionEntry, type SessionRegistry, type ShellSecretPersistence, type Signer, type StatePersistence, type SubscriptionEntry, type VerificationCacheEntry, type WindowManagerAdapter, cleanupNappState, createAclState, createEnforceGate, createEventBuffer, createManifestCache, createNappKeyRegistry, createNubEnforceGate, createReplayDetector, createRuntime, createSessionRegistry, formatDenialReason, handleStorageNub, matchesAnyFilter, matchesFilter, notifyServiceWindowDestroyed, routeServiceMessage };