@kubun/plugin-p2p 0.14.0 → 0.15.1

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.
Files changed (55) hide show
  1. package/lib/context/peer.js +250 -3
  2. package/lib/context/sync.js +134 -25
  3. package/lib/context/types.d.ts +7 -0
  4. package/lib/groups/broadcast-message.d.ts +29 -0
  5. package/lib/groups/broadcast.d.ts +11 -1
  6. package/lib/groups/broadcast.js +44 -2
  7. package/lib/groups/credential-apply.d.ts +64 -2
  8. package/lib/groups/credential-apply.js +215 -30
  9. package/lib/groups/credential-grant.d.ts +22 -0
  10. package/lib/groups/credential-grant.js +76 -2
  11. package/lib/groups/credential-manifest-token.d.ts +31 -0
  12. package/lib/groups/credential-manifest-token.js +49 -0
  13. package/lib/groups/credential-readiness.d.ts +69 -0
  14. package/lib/groups/credential-readiness.js +172 -0
  15. package/lib/groups/credential-wrapping-deps.d.ts +23 -0
  16. package/lib/groups/credential-wrapping-deps.js +25 -0
  17. package/lib/groups/did-cache-seed.d.ts +26 -0
  18. package/lib/groups/did-cache-seed.js +38 -0
  19. package/lib/groups/grantor-authority.d.ts +65 -0
  20. package/lib/groups/grantor-authority.js +107 -0
  21. package/lib/groups/group-handlers.js +7 -0
  22. package/lib/groups/group-peer-manager.d.ts +32 -1
  23. package/lib/groups/group-peer-manager.js +77 -0
  24. package/lib/groups/group-protocols.d.ts +47 -0
  25. package/lib/groups/group-protocols.js +28 -0
  26. package/lib/hub/http-client.js +6 -1
  27. package/lib/hub/hub-like.js +5 -2
  28. package/lib/hub/peer-scoped-hub-view.d.ts +6 -0
  29. package/lib/hub/peer-scoped-hub-view.js +11 -1
  30. package/lib/hub/wiring.d.ts +31 -1
  31. package/lib/hub/wiring.js +20 -1
  32. package/lib/index.d.ts +14 -0
  33. package/lib/index.js +72 -4
  34. package/lib/protocol.d.ts +30 -0
  35. package/lib/protocol.js +36 -0
  36. package/lib/schema.js +78 -1
  37. package/lib/sync/handlers.js +21 -2
  38. package/lib/sync/held-delegations.d.ts +14 -0
  39. package/lib/sync/held-delegations.js +34 -0
  40. package/lib/sync/hub-tunnel-service-listener.d.ts +84 -0
  41. package/lib/sync/hub-tunnel-service-listener.js +294 -0
  42. package/lib/sync/hub-tunnel-service-provider.d.ts +46 -0
  43. package/lib/sync/hub-tunnel-service-provider.js +100 -0
  44. package/lib/sync/hub-tunnel-sync-listener.d.ts +8 -1
  45. package/lib/sync/hub-tunnel-sync-listener.js +6 -1
  46. package/lib/sync/service-tunnel-listeners.d.ts +41 -0
  47. package/lib/sync/service-tunnel-listeners.js +183 -0
  48. package/lib/sync/sync-manager.d.ts +7 -0
  49. package/lib/sync/sync-manager.js +4 -1
  50. package/lib/sync/tunnel-listeners.d.ts +7 -1
  51. package/lib/sync/tunnel-listeners.js +18 -0
  52. package/lib/sync/tunnel-topics.d.ts +19 -1
  53. package/lib/sync/tunnel-topics.js +7 -3
  54. package/lib/types.d.ts +172 -0
  55. package/package.json +49 -48
@@ -6,6 +6,8 @@ import { createGroupPeer, RecoveryRequiredError } from '@kumiai/rpc';
6
6
  import { createHubLike } from '../hub/hub-like.js';
7
7
  import { createLoopbackLogHub } from '../hub/loopback-log-hub.js';
8
8
  import { createHubServerDIDResolver } from '../hub/server-did.js';
9
+ import { HubTunnelServiceProvider } from '../sync/hub-tunnel-service-provider.js';
10
+ import { createServiceTunnelListeners } from '../sync/service-tunnel-listeners.js';
9
11
  import { createTunnelListeners } from '../sync/tunnel-listeners.js';
10
12
  import { applyAccessDefaultSetToken } from './access-default-apply.js';
11
13
  import { createAnchorStore } from './anchor-store.js';
@@ -15,6 +17,7 @@ import { reprojectGroupSettings } from './circle-projection.js';
15
17
  import { adoptCommitJournalBlob, readJournalRequestID, settleLostControlRequest } from './commit-adoption.js';
16
18
  import { createCommitJournal } from './commit-journal.js';
17
19
  import { settleControlRequest } from './control-request.js';
20
+ import { createCredentialWrappingDeps } from './credential-wrapping-deps.js';
18
21
  import { createGroupCrypto } from './group-crypto.js';
19
22
  import { buildGroupHandlers } from './group-handlers.js';
20
23
  import { createGroupMLS } from './group-mls.js';
@@ -112,6 +115,14 @@ const peerKey = (groupID, hubURL)=>`${groupID}|${hubURL}`;
112
115
  auth: message.auth
113
116
  });
114
117
  return;
118
+ case 'credential:key-manifest':
119
+ // Both fields ride verbatim -- the token digests its own fields, so
120
+ // reshaping would break signature verification.
121
+ await peer.protocol('control').dispatch('control/credentialKeyManifest', {
122
+ manifest: message.manifest,
123
+ delegationTokens: message.delegationTokens
124
+ });
125
+ return;
115
126
  default:
116
127
  {
117
128
  // Exhaustiveness gate. A broadcast type with no case here used to fall off
@@ -466,12 +477,19 @@ export function createGroupPeerManager(params) {
466
477
  // `hasStore` because `getStore` on an unregistered name throws, and a device
467
478
  // with no credential plugin must still bind its peers.
468
479
  const credentialStore = params.stores.hasStore(CREDENTIAL_STORE) ? await getCredentialStore(params.stores) : undefined;
480
+ // Delegate-wrapping admission deps, sourced from the engine's controller
481
+ // resolver. Absent seam → empty deps → fail-closed delegated wrapping.
482
+ const credentialWrappingDeps = await createCredentialWrappingDeps(params.stores, params.controllerResolverFor);
469
483
  return {
470
484
  p2pStore,
471
485
  delegationStore,
472
486
  ...credentialStore != null ? {
473
487
  credentialStore
474
488
  } : {},
489
+ ...credentialWrappingDeps.controllerResolver != null && credentialWrappingDeps.revocationChecker != null ? {
490
+ credentialControllerResolver: credentialWrappingDeps.controllerResolver,
491
+ credentialRevocationChecker: credentialWrappingDeps.revocationChecker
492
+ } : {},
475
493
  graphStore: params.graphStore,
476
494
  graph: params.graph,
477
495
  selfDID: params.localDID,
@@ -811,6 +829,9 @@ export function createGroupPeerManager(params) {
811
829
  // Declared ahead of the presence it is triggered from, and assigned below once
812
830
  // the hub lookup it needs exists.
813
831
  let tunnelListeners;
832
+ // Same shape, service lane — see the assignment below. Reconciled on every
833
+ // trigger `tunnelListeners` is, and disposed alongside it in `stop`.
834
+ let serviceTunnelListeners;
814
835
  const presence = createPeerPresence({
815
836
  stores: params.stores,
816
837
  localDID: params.localDID,
@@ -821,6 +842,7 @@ export function createGroupPeerManager(params) {
821
842
  onProfileSet: ()=>{
822
843
  for (const groupID of joined){
823
844
  void tunnelListeners?.reconcile(groupID);
845
+ void serviceTunnelListeners?.reconcile(groupID);
824
846
  }
825
847
  },
826
848
  getGroupEpoch: (groupID)=>params.registry.groupEpoch(groupID) ?? undefined,
@@ -891,6 +913,31 @@ export function createGroupPeerManager(params) {
891
913
  localDID: params.localDID,
892
914
  runtime: tunnelRuntime,
893
915
  syncHandlers: params.syncHandlers,
916
+ ...params.cache != null ? {
917
+ cache: params.cache
918
+ } : {},
919
+ tunnelHub: (groupID)=>{
920
+ const hubURL = bindings.get(groupID)?.values().next().value;
921
+ return hubURL == null ? undefined : getHubLike(hubURL);
922
+ },
923
+ ...logger != null ? {
924
+ logger
925
+ } : {},
926
+ ...params.tunnelIdleTimeoutMs != null ? {
927
+ idleTimeoutMs: params.tunnelIdleTimeoutMs
928
+ } : {}
929
+ });
930
+ serviceTunnelListeners = params.serviceServe == null || params.services == null || tunnelRuntime == null ? undefined : createServiceTunnelListeners({
931
+ stores: params.stores,
932
+ registry: params.registry,
933
+ identity: params.identity,
934
+ localDID: params.localDID,
935
+ runtime: tunnelRuntime,
936
+ serve: params.serviceServe,
937
+ services: params.services,
938
+ ...params.cache != null ? {
939
+ cache: params.cache
940
+ } : {},
894
941
  tunnelHub: (groupID)=>{
895
942
  const hubURL = bindings.get(groupID)?.values().next().value;
896
943
  return hubURL == null ? undefined : getHubLike(hubURL);
@@ -918,6 +965,7 @@ export function createGroupPeerManager(params) {
918
965
  triggerUnsubscribes.push(params.registry.onEpochChanged((groupID)=>{
919
966
  presence.scheduleAnnounce(groupID, 'epoch-changed');
920
967
  void tunnelListeners?.reconcile(groupID);
968
+ void serviceTunnelListeners?.reconcile(groupID);
921
969
  }));
922
970
  const addGroup = async (groupID)=>{
923
971
  joined.add(groupID);
@@ -940,6 +988,7 @@ export function createGroupPeerManager(params) {
940
988
  });
941
989
  // After the peers, so the binding the listeners read exists.
942
990
  await tunnelListeners?.reconcile(groupID);
991
+ await serviceTunnelListeners?.reconcile(groupID);
943
992
  };
944
993
  /** Groups with a catch-up round already open, so the triggers cannot stack. */ const policyCatchupInFlight = new Set();
945
994
  /** Groups already asked once on connect — see {@link schedulePolicyCatchup}. */ const policyCatchupAsked = new Set();
@@ -1074,6 +1123,7 @@ export function createGroupPeerManager(params) {
1074
1123
  async removeGroup (groupID) {
1075
1124
  joined.delete(groupID);
1076
1125
  await tunnelListeners?.removeGroup(groupID);
1126
+ await serviceTunnelListeners?.removeGroup(groupID);
1077
1127
  const groupSet = bindings.get(groupID);
1078
1128
  const urls = groupSet != null ? [
1079
1129
  ...groupSet
@@ -1085,6 +1135,7 @@ export function createGroupPeerManager(params) {
1085
1135
  },
1086
1136
  async reconcileTunnelListeners (groupID) {
1087
1137
  await tunnelListeners?.reconcile(groupID);
1138
+ await serviceTunnelListeners?.reconcile(groupID);
1088
1139
  },
1089
1140
  async addBinding (groupID, hubURL) {
1090
1141
  if (!joined.has(groupID)) {
@@ -1105,12 +1156,14 @@ export function createGroupPeerManager(params) {
1105
1156
  // A group with no hub could not be dialled at all, so this is where its
1106
1157
  // members become answerable.
1107
1158
  await tunnelListeners?.reconcile(groupID);
1159
+ await serviceTunnelListeners?.reconcile(groupID);
1108
1160
  },
1109
1161
  async removeBinding (groupID, hubURL) {
1110
1162
  await disposePeer(groupID, hubURL);
1111
1163
  // The listeners hold the drain of whichever hub is bound; the one they were
1112
1164
  // built on may be the one that just left.
1113
1165
  await tunnelListeners?.reconcile(groupID);
1166
+ await serviceTunnelListeners?.reconcile(groupID);
1114
1167
  },
1115
1168
  broadcast: broadcastToPeers,
1116
1169
  async selectCommitPeer (groupID) {
@@ -1331,6 +1384,29 @@ export function createGroupPeerManager(params) {
1331
1384
  const hubURL = bindings.get(groupID)?.values().next().value;
1332
1385
  return hubURL == null ? undefined : getHubLike(hubURL);
1333
1386
  },
1387
+ async serviceTransportTo (groupID, peerDID) {
1388
+ const hub = this.tunnelHub(groupID);
1389
+ // `tunnelRuntime` mirrors `params.runtime`, which is optional here (a test
1390
+ // harness may build a manager without one) — a caller with no runtime has
1391
+ // no id generator to hand the transport, so there is no session to build.
1392
+ if (hub == null || tunnelRuntime == null) {
1393
+ return undefined;
1394
+ }
1395
+ return new HubTunnelServiceProvider({
1396
+ hub,
1397
+ registry: params.registry,
1398
+ groupID,
1399
+ localDID: params.localDID,
1400
+ peerDID,
1401
+ runtime: tunnelRuntime,
1402
+ ...params.tunnelIdleTimeoutMs != null ? {
1403
+ idleTimeoutMs: params.tunnelIdleTimeoutMs
1404
+ } : {},
1405
+ ...logger != null ? {
1406
+ logger: logger.getChild('service-tunnel-session')
1407
+ } : {}
1408
+ });
1409
+ },
1334
1410
  async retryHubs () {
1335
1411
  const live = [
1336
1412
  ...hubLikes.values()
@@ -1348,6 +1424,7 @@ export function createGroupPeerManager(params) {
1348
1424
  // Before the hubs go: each listener holds a subscription on one of them,
1349
1425
  // and its spawn loop re-arms until it is told to stop.
1350
1426
  await tunnelListeners?.dispose();
1427
+ await serviceTunnelListeners?.dispose();
1351
1428
  for (const off of triggerUnsubscribes.splice(0)){
1352
1429
  try {
1353
1430
  off();
@@ -310,6 +310,29 @@ export declare const controlProtocol: {
310
310
  readonly additionalProperties: false;
311
311
  };
312
312
  };
313
+ readonly 'control/credentialKeyManifest': {
314
+ readonly type: "event";
315
+ readonly retain: "log";
316
+ readonly description: "A grantor's advisory record of the key set it granted a recipient (the readiness union). `manifest` is the grantor's signed token; `delegationTokens` proves its administer chain over the owner. Group-wide because the receiver keys the row on the manifest's own owner/recipient/grantor. The manifest authorizes nothing — the receiver's gate keeps a bogus one out of the store.";
317
+ readonly data: {
318
+ readonly type: "object";
319
+ readonly properties: {
320
+ readonly manifest: {
321
+ readonly type: "string";
322
+ readonly description: "The grantor's signed manifest token; its issuer is the authoritative grantor.";
323
+ };
324
+ readonly delegationTokens: {
325
+ readonly type: "array";
326
+ readonly items: {
327
+ readonly type: "string";
328
+ };
329
+ readonly description: "The grantor's administer-chain delegation tokens, closest-to-grantor first. Empty when the grantor is the owner.";
330
+ };
331
+ };
332
+ readonly required: readonly ["manifest", "delegationTokens"];
333
+ readonly additionalProperties: false;
334
+ };
335
+ };
313
336
  readonly 'control/groupLeaveRequest': {
314
337
  readonly type: "event";
315
338
  readonly retain: "ephemeral";
@@ -494,6 +517,7 @@ export type DelegationRevokeData = FromSchema<(typeof controlProtocol)['control/
494
517
  export type AccessDefaultSetData = FromSchema<(typeof controlProtocol)['control/accessDefaultSet']['data']>;
495
518
  export type AccessDefaultRemoveData = FromSchema<(typeof controlProtocol)['control/accessDefaultRemove']['data']>;
496
519
  export type CredentialKeyGrantData = FromSchema<(typeof controlProtocol)['control/credentialKeyGrant']['data']>;
520
+ export type CredentialKeyManifestData = FromSchema<(typeof controlProtocol)['control/credentialKeyManifest']['data']>;
497
521
  export type GroupLeaveRequestData = FromSchema<(typeof controlProtocol)['control/groupLeaveRequest']['data']>;
498
522
  export type MutationApplyData = FromSchema<(typeof syncProtocol)['sync/mutationApply']['data']>;
499
523
  export type PeerAnnounceData = FromSchema<(typeof peerProtocol)['peer/announce']['data']>;
@@ -806,6 +830,29 @@ export declare const groupProtocols: {
806
830
  readonly additionalProperties: false;
807
831
  };
808
832
  };
833
+ readonly 'control/credentialKeyManifest': {
834
+ readonly type: "event";
835
+ readonly retain: "log";
836
+ readonly description: "A grantor's advisory record of the key set it granted a recipient (the readiness union). `manifest` is the grantor's signed token; `delegationTokens` proves its administer chain over the owner. Group-wide because the receiver keys the row on the manifest's own owner/recipient/grantor. The manifest authorizes nothing — the receiver's gate keeps a bogus one out of the store.";
837
+ readonly data: {
838
+ readonly type: "object";
839
+ readonly properties: {
840
+ readonly manifest: {
841
+ readonly type: "string";
842
+ readonly description: "The grantor's signed manifest token; its issuer is the authoritative grantor.";
843
+ };
844
+ readonly delegationTokens: {
845
+ readonly type: "array";
846
+ readonly items: {
847
+ readonly type: "string";
848
+ };
849
+ readonly description: "The grantor's administer-chain delegation tokens, closest-to-grantor first. Empty when the grantor is the owner.";
850
+ };
851
+ };
852
+ readonly required: readonly ["manifest", "delegationTokens"];
853
+ readonly additionalProperties: false;
854
+ };
855
+ };
809
856
  readonly 'control/groupLeaveRequest': {
810
857
  readonly type: "event";
811
858
  readonly retain: "ephemeral";
@@ -395,6 +395,34 @@ import { defineGroupProtocol } from '@kumiai/rpc';
395
395
  additionalProperties: false
396
396
  }
397
397
  },
398
+ 'control/credentialKeyManifest': {
399
+ type: 'event',
400
+ // Retained like the grant: an offline recipient must still find this on
401
+ // the epoch's app topic later, so it costs one log frame.
402
+ retain: 'log',
403
+ description: "A grantor's advisory record of the key set it granted a recipient (the readiness union). `manifest` is the grantor's signed token; `delegationTokens` proves its administer chain over the owner. Group-wide because the receiver keys the row on the manifest's own owner/recipient/grantor. The manifest authorizes nothing — the receiver's gate keeps a bogus one out of the store.",
404
+ data: {
405
+ type: 'object',
406
+ properties: {
407
+ manifest: {
408
+ type: 'string',
409
+ description: "The grantor's signed manifest token; its issuer is the authoritative grantor."
410
+ },
411
+ delegationTokens: {
412
+ type: 'array',
413
+ items: {
414
+ type: 'string'
415
+ },
416
+ description: "The grantor's administer-chain delegation tokens, closest-to-grantor first. Empty when the grantor is the owner."
417
+ }
418
+ },
419
+ required: [
420
+ 'manifest',
421
+ 'delegationTokens'
422
+ ],
423
+ additionalProperties: false
424
+ }
425
+ },
398
426
  'control/groupLeaveRequest': {
399
427
  type: 'event',
400
428
  retain: 'ephemeral',
@@ -9,7 +9,12 @@ export function createHTTPHubClient(params) {
9
9
  return new Client({
10
10
  transport,
11
11
  identity: params.identity,
12
- serverID: opts?.serverID ?? params.serverID
12
+ serverID: opts?.serverID ?? params.serverID,
13
+ // The hub is a blind relay: no MLS roster, and a `Server` whose DID cache
14
+ // cannot be relied on across this client's reconnect churn. Embed the long
15
+ // form on every hub-facing token so a `did:peer:4` device's short-form
16
+ // `iss` self-resolves at the hub instead of throwing `Unknown DID`.
17
+ embedLongForm: true
13
18
  });
14
19
  };
15
20
  }
@@ -1,5 +1,6 @@
1
1
  import { RequestError } from '@enkaku/client';
2
2
  import { ErrorCodes } from '@enkaku/protocol';
3
+ import { normalizeDID } from '@kokuin/token';
3
4
  import { hubErrorFromCode, RetentionExceededError } from '@kumiai/hub-protocol';
4
5
  import { fromB64, toB64 } from '@sozai/codec';
5
6
  import { EventEmitter } from '@sozai/event';
@@ -79,14 +80,16 @@ function rethrowHubError(error) {
79
80
  #senderDID;
80
81
  #topicID;
81
82
  constructor(options){
82
- this.#senderDID = options?.senderDID;
83
+ // Canonicalize the scope so a peer:4 sender attested by its long form (an
84
+ // embed-long-form hub client) still matches its short-form route DID.
85
+ this.#senderDID = options?.senderDID == null ? undefined : normalizeDID(options.senderDID);
83
86
  this.#topicID = options?.topicID;
84
87
  }
85
88
  push(message) {
86
89
  if (this.#stopped) {
87
90
  return;
88
91
  }
89
- if (this.#senderDID != null && message.senderDID !== this.#senderDID) {
92
+ if (this.#senderDID != null && normalizeDID(message.senderDID) !== this.#senderDID) {
90
93
  return;
91
94
  }
92
95
  if (this.#topicID != null && message.topicID !== this.#topicID) {
@@ -25,6 +25,12 @@ export type PeerScopedHubViewParams = {
25
25
  * MLS-authenticated identity. That is enough: the filter routes, MLS still
26
26
  * authorizes, and a hostile hub could only hide frames it can already drop.
27
27
  *
28
+ * Both sides are normalized before the match: a `did:peer:4` publisher whose hub
29
+ * client embeds the long form is attested by its long form, while `peerDID` is
30
+ * the roster's short form — a raw `===` would drop every such frame, and its
31
+ * request would vanish with no error (the exact failure this filter is meant to
32
+ * prevent for the OTHER peer's frames).
33
+ *
28
34
  * **`unsubscribe` is dropped.** The responder topic belongs to the (group,
29
35
  * epoch), not to a session: every listener on the device shares it, one per
30
36
  * co-member, and each respawns independently — so a departing transport must not
@@ -1,3 +1,4 @@
1
+ import { normalizeDID } from '@kokuin/token';
1
2
  /**
2
3
  * A view over one device's hub that surfaces only the frames one peer sent.
3
4
  *
@@ -18,6 +19,12 @@
18
19
  * MLS-authenticated identity. That is enough: the filter routes, MLS still
19
20
  * authorizes, and a hostile hub could only hide frames it can already drop.
20
21
  *
22
+ * Both sides are normalized before the match: a `did:peer:4` publisher whose hub
23
+ * client embeds the long form is attested by its long form, while `peerDID` is
24
+ * the roster's short form — a raw `===` would drop every such frame, and its
25
+ * request would vanish with no error (the exact failure this filter is meant to
26
+ * prevent for the OTHER peer's frames).
27
+ *
21
28
  * **`unsubscribe` is dropped.** The responder topic belongs to the (group,
22
29
  * epoch), not to a session: every listener on the device shares it, one per
23
30
  * co-member, and each respawns independently — so a departing transport must not
@@ -26,6 +33,9 @@
26
33
  * therefore issued once per topic and held for the life of the view.
27
34
  */ export function createPeerScopedHubView({ hub, peerDID }) {
28
35
  const armed = new Set();
36
+ // Match on the canonical form so a peer:4 sender attested by its long form
37
+ // (an embed-long-form hub client) still routes to its short-form roster entry.
38
+ const scopedDID = normalizeDID(peerDID);
29
39
  const view = {
30
40
  publish: (params)=>hub.publish(params),
31
41
  subscribe: async (subscriberDID, topicID, options)=>{
@@ -58,7 +68,7 @@
58
68
  done: true
59
69
  };
60
70
  }
61
- if (result.value.senderDID === peerDID) {
71
+ if (normalizeDID(result.value.senderDID) === scopedDID) {
62
72
  return result;
63
73
  }
64
74
  }
@@ -1,18 +1,22 @@
1
+ import type { ClientTransportOf } from '@enkaku/protocol';
1
2
  import type { ProcedureHandlers } from '@enkaku/server';
2
- import type { OwnIdentity } from '@kokuin/token';
3
+ import type { DIDCache, OwnIdentity } from '@kokuin/token';
3
4
  import type { KubunDB } from '@kubun/db';
4
5
  import type { DefaultAccessLevel, GraphInternals } from '@kubun/engine';
5
6
  import type { HLC } from '@kubun/hlc';
6
7
  import type { Logger } from '@kubun/logger';
8
+ import type { ServiceConfig, ServiceProtocol } from '@kubun/plugin-service-api';
7
9
  import type { LaneResult, PendingCommit } from '@kumiai/rpc';
8
10
  import type { Runtime } from '@sozai/runtime';
9
11
  import type { GroupBroadcastMessage } from '../groups/broadcast-message.js';
12
+ import type { ControllerResolverFor } from '../groups/credential-wrapping-deps.js';
10
13
  import type { P2PEventEmitter } from '../groups/events.js';
11
14
  import type { GroupHandleRegistry } from '../groups/group-handle-registry.js';
12
15
  import type { BuildLedgerRedrive } from '../groups/group-peer-manager.js';
13
16
  import type { PeerPresence } from '../groups/peer-presence.js';
14
17
  import type { SyncProtocol } from '../protocol.js';
15
18
  import type { ForwardingConfig } from '../sync/forwarder.js';
19
+ import type { ServeService } from '../sync/hub-tunnel-service-listener.js';
16
20
  import type { SyncTransportProvider } from '../sync/sync-client.js';
17
21
  import type { LedgerCatchupOptions, LedgerCatchupSummary, RejoinResult, StoreUnreadableMode } from '../types.js';
18
22
  import type { CreateHubClient } from './http-client.js';
@@ -65,6 +69,12 @@ export type HubWiring = {
65
69
  * carries is authorized per document at the far end exactly as an HTTP one is.
66
70
  */
67
71
  syncTransportTo: (groupID: string, peerDID: string) => Promise<SyncTransportProvider | undefined>;
72
+ /**
73
+ * Build the transport for one directed SERVICE-lane session to a co-member,
74
+ * relayed by the group's hub — the mirror of {@link syncTransportTo} on the
75
+ * service lane. `undefined` when the group has no hub bound.
76
+ */
77
+ serviceTransportTo: (groupID: string, peerDID: string) => Promise<ClientTransportOf<ServiceProtocol> | undefined>;
68
78
  dispose: () => Promise<void>;
69
79
  };
70
80
  export type SetupHubRelayParams = {
@@ -113,6 +123,12 @@ export type SetupHubRelayParams = {
113
123
  * stamp is bounded there the same way the graph lane bounds a mutation's.
114
124
  */
115
125
  maxDriftMS: number;
126
+ /**
127
+ * The engine's `did:kokuin:` controller-resolver seam, forwarded to the apply
128
+ * path so a delegate-signed `credential:key-grant` wrapping can be authorized.
129
+ * Omitted, the delegated wrapping stays fail-closed.
130
+ */
131
+ controllerResolverFor?: ControllerResolverFor;
116
132
  /**
117
133
  * Reconnect-backoff overrides forwarded to every hub adapter. Test-only; when
118
134
  * omitted the adapter runs on its production defaults.
@@ -130,5 +146,19 @@ export type SetupHubRelayParams = {
130
146
  * answers none.
131
147
  */
132
148
  syncHandlers?: ProcedureHandlers<SyncProtocol>;
149
+ /**
150
+ * Injected `plugin-service-server` `serve()`, for answering an inbound
151
+ * service-lane tunnel session — see {@link ServeService}. Paired with
152
+ * `services`: both present is what serves the lane.
153
+ */
154
+ serviceServe?: ServeService;
155
+ /** Which services to serve on an inbound service-lane session. */
156
+ services?: Record<string, ServiceConfig>;
157
+ /**
158
+ * Shared, plugin-lifetime DID cache forwarded to the group peer manager's
159
+ * tunnel listeners so a co-member's short-form `did:peer:4` issuer resolves on
160
+ * a spawned session's Server.
161
+ */
162
+ cache?: DIDCache;
133
163
  };
134
164
  export declare function setupHubRelay(params: SetupHubRelayParams): HubWiring;
package/lib/hub/wiring.js CHANGED
@@ -10,7 +10,7 @@ import { HubTunnelSyncProvider } from '../sync/hub-tunnel-sync-provider.js';
10
10
  * once per candidate before reporting `no-route`.
11
11
  */ const DEFAULT_TUNNEL_IDLE_TIMEOUT_MS = 30_000;
12
12
  export function setupHubRelay(params) {
13
- const { identity, runtime, db, graph, emitter, createHubClient, registry, buildLedgerRedrive, logger, storeUnreadable, defaultAccessLevel, forwarding, hlc, maxDriftMS, hubReconnectBackoff, tunnelIdleTimeoutMs } = params;
13
+ const { identity, runtime, db, graph, emitter, createHubClient, registry, buildLedgerRedrive, logger, storeUnreadable, defaultAccessLevel, forwarding, hlc, maxDriftMS, controllerResolverFor, hubReconnectBackoff, tunnelIdleTimeoutMs } = params;
14
14
  const unsubscribes = [];
15
15
  // Late-bound `ready` resolving to the live manager. The fire-and-forget
16
16
  // schedulers chain off it so a caller can enqueue work before boot completes;
@@ -68,6 +68,10 @@ export function setupHubRelay(params) {
68
68
  logger: logger.getChild('tunnel-session')
69
69
  });
70
70
  };
71
+ const serviceTransportTo = async (groupID, peerDID)=>{
72
+ const provider = await (await ready).serviceTransportTo(groupID, peerDID);
73
+ return provider == null ? undefined : await provider.createServiceTransport();
74
+ };
71
75
  ready = (async ()=>{
72
76
  const [p2pStore, graphStore] = await Promise.all([
73
77
  db.getStore('p2p'),
@@ -90,6 +94,9 @@ export function setupHubRelay(params) {
90
94
  storeUnreadable,
91
95
  defaultAccessLevel,
92
96
  forwarding,
97
+ ...controllerResolverFor != null ? {
98
+ controllerResolverFor
99
+ } : {},
93
100
  // The manager's own fan-out, reached through the same late-bound `ready`
94
101
  // every other scheduler chains off — a forward is one more broadcast, so
95
102
  // it takes the path a locally-authored one already takes.
@@ -102,6 +109,17 @@ export function setupHubRelay(params) {
102
109
  ...params.syncHandlers != null ? {
103
110
  syncHandlers: params.syncHandlers
104
111
  } : {},
112
+ // The service lane's answering half; both present is what serves it,
113
+ // either absent and no service listeners stand up.
114
+ ...params.serviceServe != null ? {
115
+ serviceServe: params.serviceServe
116
+ } : {},
117
+ ...params.services != null ? {
118
+ services: params.services
119
+ } : {},
120
+ ...params.cache != null ? {
121
+ cache: params.cache
122
+ } : {},
105
123
  tunnelIdleTimeoutMs: tunnelIdleTimeoutMs ?? DEFAULT_TUNNEL_IDLE_TIMEOUT_MS
106
124
  });
107
125
  unsubscribes.push(emitter.on('groupJoined', (group)=>manager.addGroup(group.id).catch((error)=>{
@@ -170,6 +188,7 @@ export function setupHubRelay(params) {
170
188
  presence,
171
189
  retryHubs,
172
190
  syncTransportTo,
191
+ serviceTransportTo,
173
192
  dispose: async ()=>{
174
193
  for (const off of unsubscribes){
175
194
  try {
package/lib/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { DefaultAccessLevel, KubunPlugin, PluginFactoryParams } from '@kubun/engine';
2
+ import type { ServiceConfig } from '@kubun/plugin-service-api';
2
3
  import { type CreateHubClient } from './hub/http-client.js';
3
4
  import { type BroadcastBatchConfig } from './sync/broadcast-queue.js';
4
5
  import { type PushSyncConfig } from './sync/broadcast-sender.js';
@@ -172,5 +173,18 @@ export type P2PPluginOptions = {
172
173
  * which a headless test would otherwise have to wait out per offline peer.
173
174
  */
174
175
  tunnelIdleTimeoutMs?: number;
176
+ /**
177
+ * Serve service-lane sessions over the hub tunnel, on a distinct protocol
178
+ * from sync so ratchet generation is never shared. Requires the
179
+ * `service-server` plugin; `serviceTransportTo` still resolves for dialing
180
+ * out even when this device serves nothing.
181
+ * - `true` / `{}` — serve `{ 'controller-log': true }`.
182
+ * - `{ services }` — serve exactly this config (falls back to
183
+ * `{ 'controller-log': true }` when `services` is omitted).
184
+ * - absent / `false` (default) — no service-lane listener.
185
+ */
186
+ serviceTunnel?: boolean | {
187
+ services?: Record<string, ServiceConfig>;
188
+ };
175
189
  };
176
190
  export declare function createP2PPlugin(options?: P2PPluginOptions): (params: PluginFactoryParams) => KubunPlugin;