pico-engine 1.6.2 → 1.8.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.
Files changed (107) hide show
  1. package/README.md +117 -14
  2. package/dist/RulesetRegistryLoaderFs.js +24 -8
  3. package/dist/auth/cookies.js +32 -0
  4. package/dist/auth/index.js +6 -1
  5. package/dist/bundledKrl.js +129 -11
  6. package/dist/channelIdentityPolicy.js +22 -0
  7. package/dist/cli.js +105 -46
  8. package/dist/engineConfig.js +280 -0
  9. package/dist/identity/IdentityService.js +90 -0
  10. package/dist/identity/crossPico.js +106 -30
  11. package/dist/identity/didoModule.js +80 -18
  12. package/dist/identity/establishSubscription.js +2 -2
  13. package/dist/identity/identityPortable.js +92 -0
  14. package/dist/identity/index.js +10 -1
  15. package/dist/identity/localPeerReconcile.js +65 -0
  16. package/dist/identity/peerDid4.js +175 -0
  17. package/dist/identity/peerDid4Create.js +90 -0
  18. package/dist/identity/portableExportPrepare.js +196 -0
  19. package/dist/identity/portableMove.js +87 -0
  20. package/dist/identity/skyIntro.js +10 -4
  21. package/dist/identity/skyProtocol.js +26 -1
  22. package/dist/identity/skyRotation.js +121 -0
  23. package/dist/identity/store.js +5 -1
  24. package/dist/identity/subscriptionEntSync.js +72 -0
  25. package/dist/identity/veramoDidComm.js +41 -2
  26. package/dist/identity/webvh.js +4 -2
  27. package/dist/identity/webvhRelocation.js +115 -0
  28. package/dist/index.js +127 -34
  29. package/dist/levelDb.js +102 -0
  30. package/dist/logging.js +47 -8
  31. package/dist/oauth/OAuthService.js +12 -5
  32. package/dist/oauth/channelEligibility.js +7 -1
  33. package/dist/oauth/index.js +3 -1
  34. package/dist/policyConfigFromJson.js +112 -0
  35. package/dist/runMcp.js +27 -0
  36. package/dist/server.js +95 -24
  37. package/dist/subtreeWrangler.js +180 -0
  38. package/dist/uiChannelPolicies.js +16 -0
  39. package/krl/io.picolabs.oauth.krl +51 -5
  40. package/krl/io.picolabs.pds.krl +131 -10
  41. package/krl/io.picolabs.pico-engine-ui.krl +219 -22
  42. package/krl/io.picolabs.portable_subtree.krl +97 -0
  43. package/krl/io.picolabs.subscription.krl +226 -72
  44. package/krl/io.picolabs.wrangler.krl +300 -58
  45. package/mcp/devResources.js +118 -0
  46. package/mcp/devTools.js +351 -0
  47. package/mcp/engineClient.js +133 -0
  48. package/mcp/meshHttp.js +137 -0
  49. package/mcp/meshTools.js +189 -0
  50. package/mcp/runStdio.js +34 -0
  51. package/mcp/schemaToZod.js +56 -0
  52. package/package.json +22 -8
  53. package/public/docs/_sidebar.md +2 -1
  54. package/public/docs/llms-full.txt +479 -0
  55. package/public/docs/llms.txt +37 -0
  56. package/public/docs/openapi.yaml +78 -0
  57. package/public/docs/pico-engine.md +235 -4
  58. package/public/docs/pico-overview.md +117 -0
  59. package/public/docs/pico.md +3 -1
  60. package/public/docs/rulesets/README.md +25 -0
  61. package/public/docs/rulesets/io.picolabs.oauth.md +71 -0
  62. package/public/docs/rulesets/io.picolabs.pds.md +327 -0
  63. package/public/docs/rulesets/io.picolabs.pico-engine-ui.md +65 -0
  64. package/public/docs/rulesets/io.picolabs.portable_subtree.md +94 -0
  65. package/public/docs/rulesets/io.picolabs.subscription.md +398 -0
  66. package/public/docs/rulesets/io.picolabs.wrangler.md +471 -0
  67. package/public/pico-engine-ui.css +1 -1
  68. package/public/pico-engine-ui.js +28 -26
  69. package/src/RulesetRegistryLoaderFs.ts +43 -11
  70. package/src/auth/cookies.ts +34 -0
  71. package/src/auth/index.ts +7 -0
  72. package/src/bundledKrl.ts +150 -12
  73. package/src/channelIdentityPolicy.ts +29 -0
  74. package/src/cli.ts +98 -40
  75. package/src/engineConfig.ts +345 -0
  76. package/src/identity/IdentityService.ts +189 -1
  77. package/src/identity/crossPico.ts +161 -41
  78. package/src/identity/didoModule.ts +140 -23
  79. package/src/identity/establishSubscription.ts +2 -2
  80. package/src/identity/identityPortable.ts +153 -0
  81. package/src/identity/index.ts +14 -0
  82. package/src/identity/localPeerReconcile.ts +97 -0
  83. package/src/identity/peerDid4.ts +197 -0
  84. package/src/identity/peerDid4Create.ts +121 -0
  85. package/src/identity/portableExportPrepare.ts +302 -0
  86. package/src/identity/portableMove.ts +193 -0
  87. package/src/identity/skyIntro.ts +16 -12
  88. package/src/identity/skyProtocol.ts +46 -0
  89. package/src/identity/skyRotation.ts +211 -0
  90. package/src/identity/store.ts +5 -1
  91. package/src/identity/subscriptionEntSync.ts +97 -0
  92. package/src/identity/veramoDidComm.ts +52 -2
  93. package/src/identity/webvh.ts +4 -4
  94. package/src/identity/webvhRelocation.ts +167 -0
  95. package/src/index.ts +179 -39
  96. package/src/levelDb.ts +122 -0
  97. package/src/logging.ts +63 -11
  98. package/src/oauth/OAuthService.ts +20 -6
  99. package/src/oauth/channelEligibility.ts +9 -0
  100. package/src/oauth/index.ts +7 -1
  101. package/src/policyConfigFromJson.ts +131 -0
  102. package/src/runMcp.ts +30 -0
  103. package/src/server.ts +133 -27
  104. package/src/subtreeWrangler.ts +278 -0
  105. package/src/uiChannelPolicies.ts +16 -0
  106. package/krl/io.picolabs.did-o.krl +0 -349
  107. package/krl/test/didtestdid.krl +0 -78
@@ -35,7 +35,7 @@ export interface CrossPicoDeps {
35
35
  }
36
36
 
37
37
  function remotePeerDid(sub: PeerSubscriptionRecord): string {
38
- const did = sub.remotePeerDid || sub.remoteDid;
38
+ const did = sub.remotePeerDid || sub.remoteDid || sub.remoteWebvhDid;
39
39
  if (!did) {
40
40
  throw new IdentityError("Subscription missing remote peer DID", 400);
41
41
  }
@@ -47,13 +47,32 @@ function remoteTxHost(sub: PeerSubscriptionRecord, fallback: string): string {
47
47
  return host.replace(/\/$/, "");
48
48
  }
49
49
 
50
+ function normalizeBaseUrl(url: string): string {
51
+ return url.replace(/\/$/, "");
52
+ }
53
+
54
+ /** Peer lives on another engine when identity store says so (post-move rotate). */
55
+ function peerOnRemoteEngine(
56
+ sub: PeerSubscriptionRecord,
57
+ localBaseUrl: string
58
+ ): boolean {
59
+ if (!sub.remoteTxHost) {
60
+ return false;
61
+ }
62
+ return normalizeBaseUrl(sub.remoteTxHost) !== normalizeBaseUrl(localBaseUrl);
63
+ }
64
+
50
65
  export async function usesLocalDispatch(
51
66
  store: IdentityStore,
52
67
  pf: PicoFramework,
53
68
  fromPicoId: string,
54
69
  toPicoId: string,
55
- sub: PeerSubscriptionRecord
70
+ sub: PeerSubscriptionRecord,
71
+ localBaseUrl: string
56
72
  ): Promise<boolean> {
73
+ if (peerOnRemoteEngine(sub, localBaseUrl)) {
74
+ return false;
75
+ }
57
76
  const fromMesh = await store.getMeshRootId(fromPicoId);
58
77
  const toMesh = await store.getMeshRootId(toPicoId);
59
78
  if (!fromMesh || !toMesh || fromMesh !== toMesh) {
@@ -69,20 +88,22 @@ export async function resolveRecipientPicoId(
69
88
  store: IdentityStore,
70
89
  pf: PicoFramework,
71
90
  fromPicoId: string,
72
- subscriptionId: string
91
+ subscriptionId: string,
92
+ localBaseUrl: string
73
93
  ): Promise<string | undefined> {
74
94
  const sub = await store.getPeerSubscription(fromPicoId, subscriptionId);
75
95
  if (!sub) {
76
96
  return undefined;
77
97
  }
98
+ const remoteEngine = peerOnRemoteEngine(sub, localBaseUrl);
78
99
  const remotePeer = sub.remotePeerDid || sub.remoteDid;
79
- if (remotePeer) {
100
+ if (remotePeer && !remoteEngine) {
80
101
  const byPeer = await store.findPicoIdByLocalPeerDid(remotePeer);
81
102
  if (byPeer && pf.loadedPicos().some((p) => p.id === byPeer)) {
82
103
  return byPeer;
83
104
  }
84
105
  }
85
- if (sub.remoteWebvhDid) {
106
+ if (sub.remoteWebvhDid && !remoteEngine) {
86
107
  const byWebvh = await store.findPicoIdByWebvhDid(sub.remoteWebvhDid);
87
108
  if (byWebvh && pf.loadedPicos().some((p) => p.id === byWebvh)) {
88
109
  return byWebvh;
@@ -106,28 +127,59 @@ export async function crossPicoEvent(
106
127
  const callerDid = await deps.store.getWebvhDid(fromPicoId);
107
128
  const attrs = { ...(event.attrs || {}), callerDid: callerDid || undefined };
108
129
 
130
+ const localBase = deps.getBaseUrl();
109
131
  const to =
110
132
  toPicoId ||
111
- (await resolveRecipientPicoId(deps.store, deps.pf, fromPicoId, subscriptionId));
133
+ (await resolveRecipientPicoId(
134
+ deps.store,
135
+ deps.pf,
136
+ fromPicoId,
137
+ subscriptionId,
138
+ localBase
139
+ ));
112
140
 
113
141
  if (
114
142
  to &&
115
- (await usesLocalDispatch(deps.store, deps.pf, fromPicoId, to, sub))
143
+ (await usesLocalDispatch(
144
+ deps.store,
145
+ deps.pf,
146
+ fromPicoId,
147
+ to,
148
+ sub,
149
+ localBase
150
+ ))
116
151
  ) {
117
- const recipientSub = await findRecipientSub(deps.store, to, subscriptionId);
118
- return deps.pf.eventWait(
119
- {
120
- eci: recipientSub.rxEci!,
121
- domain: event.domain,
122
- name: event.name,
123
- data: { attrs },
124
- time: 0,
125
- },
126
- fromPicoId
127
- );
152
+ const rxEci = await resolveRecipientRxEci(deps, to, subscriptionId);
153
+ if (rxEci) {
154
+ return deps.pf.eventWait(
155
+ {
156
+ eci: rxEci,
157
+ domain: event.domain,
158
+ name: event.name,
159
+ data: { attrs },
160
+ time: 0,
161
+ },
162
+ fromPicoId
163
+ );
164
+ }
165
+ }
166
+
167
+ try {
168
+ return await sendSkyEvent(deps, fromPicoId, sub, event, attrs);
169
+ } catch (err) {
170
+ if (isRemovalNotification(event.name)) {
171
+ return { eid: "none", responses: [] };
172
+ }
173
+ throw err;
128
174
  }
175
+ }
129
176
 
130
- return sendSkyEvent(deps, fromPicoId, sub, event, attrs);
177
+ function isRemovalNotification(name: string): boolean {
178
+ return (
179
+ name === "inbound_removal" ||
180
+ name === "outbound_removal" ||
181
+ name === "established_removal"
182
+ );
131
183
  }
132
184
 
133
185
  export async function crossPicoQuery(
@@ -142,42 +194,110 @@ export async function crossPicoQuery(
142
194
  throw new IdentityError(`Unknown subscription ${subscriptionId}`, 404);
143
195
  }
144
196
 
197
+ const localBase = deps.getBaseUrl();
145
198
  const to =
146
199
  toPicoId ||
147
- (await resolveRecipientPicoId(deps.store, deps.pf, fromPicoId, subscriptionId));
200
+ (await resolveRecipientPicoId(
201
+ deps.store,
202
+ deps.pf,
203
+ fromPicoId,
204
+ subscriptionId,
205
+ localBase
206
+ ));
148
207
 
149
208
  if (
150
209
  to &&
151
- (await usesLocalDispatch(deps.store, deps.pf, fromPicoId, to, sub))
210
+ (await usesLocalDispatch(
211
+ deps.store,
212
+ deps.pf,
213
+ fromPicoId,
214
+ to,
215
+ sub,
216
+ localBase
217
+ ))
152
218
  ) {
153
- const recipientSub = await findRecipientSub(deps.store, to, subscriptionId);
154
- return deps.pf.query(
155
- {
156
- eci: recipientSub.rxEci!,
157
- rid: query.rid,
158
- name: query.name,
159
- args: query.args || {},
160
- },
161
- fromPicoId
162
- );
219
+ const rxEci = await resolveRecipientRxEci(deps, to, subscriptionId);
220
+ if (rxEci) {
221
+ return deps.pf.query(
222
+ {
223
+ eci: rxEci,
224
+ rid: query.rid,
225
+ name: query.name,
226
+ args: query.args || {},
227
+ },
228
+ fromPicoId
229
+ );
230
+ }
163
231
  }
164
232
 
165
233
  return sendSkyQuery(deps, fromPicoId, sub, query);
166
234
  }
167
235
 
168
- async function findRecipientSub(
169
- store: IdentityStore,
236
+ function deliveryEci(
237
+ pf: PicoFramework,
238
+ picoId: string,
239
+ preferred?: string
240
+ ): string {
241
+ if (preferred) {
242
+ return preferred;
243
+ }
244
+ const pico = pf.loadedPicos().find((p) => p.id === picoId);
245
+ if (!pico) {
246
+ throw new IdentityError(`Pico ${picoId} not loaded`, 404);
247
+ }
248
+ for (const ch of Object.values(pico.channels)) {
249
+ const ro = ch.toReadOnly();
250
+ if (ro.tags.includes("wellKnown_Rx")) {
251
+ return ro.id;
252
+ }
253
+ }
254
+ for (const ch of Object.values(pico.channels)) {
255
+ const ro = ch.toReadOnly();
256
+ if (ro.tags.includes("allow-all")) {
257
+ return ro.id;
258
+ }
259
+ }
260
+ const first = Object.keys(pico.channels)[0];
261
+ if (!first) {
262
+ throw new IdentityError("Pico has no channel for cross-pico delivery", 404);
263
+ }
264
+ return first;
265
+ }
266
+
267
+ /** Resolve Rx ECI on the recipient for local dispatch (identity store, then inbound bus). */
268
+ async function resolveRecipientRxEci(
269
+ deps: CrossPicoDeps,
170
270
  toPicoId: string,
171
271
  subscriptionId: string
172
- ): Promise<PeerSubscriptionRecord> {
173
- const recipientSub = await store.getPeerSubscription(toPicoId, subscriptionId);
174
- if (!recipientSub?.rxEci) {
175
- throw new IdentityError(
176
- `Recipient subscription ${subscriptionId} missing rxEci`,
177
- 404
178
- );
272
+ ): Promise<string | undefined> {
273
+ const recipientSub = await deps.store.getPeerSubscription(
274
+ toPicoId,
275
+ subscriptionId
276
+ );
277
+ if (recipientSub?.rxEci) {
278
+ return recipientSub.rxEci;
279
+ }
280
+
281
+ try {
282
+ const queryEci = deliveryEci(deps.pf, toPicoId, recipientSub?.rxEci);
283
+ const inbound = (await deps.pf.query(
284
+ {
285
+ eci: queryEci,
286
+ rid: "io.picolabs.subscription",
287
+ name: "inbound",
288
+ args: {},
289
+ },
290
+ toPicoId
291
+ )) as Array<{ Id?: string; Rx?: string }>;
292
+ const bus = inbound.find((b) => b.Id === subscriptionId);
293
+ if (typeof bus?.Rx === "string" && bus.Rx.length > 0) {
294
+ return bus.Rx;
295
+ }
296
+ } catch {
297
+ // fall through to DIDComm or no-op
179
298
  }
180
- return recipientSub;
299
+
300
+ return undefined;
181
301
  }
182
302
 
183
303
  async function sendSkyEvent(
@@ -1,6 +1,22 @@
1
+ /**
2
+ * Engine global KRL module `dido` — the ruleset-facing bridge to IdentityService.
3
+ *
4
+ * Wrangler and subscription call `dido:*` for Layer 2 identity: did:webvh lookup,
5
+ * SKY intro/response, cross-pico query/event, DIDComm pack/unpack/route, and
6
+ * portable-move helpers. State lives in the engine identity store, not in KRL ent.
7
+ *
8
+ * Not the retired `io.picolabs.did-o` ruleset (removed in 1.7). Do not rename this
9
+ * module; it is internal OS plumbing wired at engine start via core.modules["dido"].
10
+ */
11
+
1
12
  import { krl } from "krl-stdlib";
2
13
  import { IdentityService } from "./IdentityService";
3
14
  import { IdentityError } from "./errors";
15
+ import type {
16
+ SubtreeImportOptions,
17
+ SubtreeImportResult,
18
+ } from "pico-engine-core";
19
+ import type { RelocateWebvhOptions } from "./webvhRelocation";
4
20
 
5
21
  const QUERY_TIMEOUT = 10000;
6
22
 
@@ -103,8 +119,6 @@ export default function initDidoModule(identity: IdentityService) {
103
119
  return undefined;
104
120
  }),
105
121
 
106
- prepareQuery: deprecated("prepareQuery"),
107
-
108
122
  sendQuery: krl.Function(["did", "message"], async function (
109
123
  did: string,
110
124
  message: any
@@ -332,32 +346,135 @@ export default function initDidoModule(identity: IdentityService) {
332
346
  });
333
347
  }),
334
348
 
335
- // Legacy did-o / did:peer:2 surface — removed in Layer 2 reboot.
336
- generateDID: deprecated("generateDID"),
337
- deleteDID: deprecated("deleteDID"),
338
- updateDID: deprecated("updateDID"),
339
- rotateDID: deprecated("rotateDID"),
340
- rotateInviteDID: deprecated("rotateInviteDID"),
341
- clearPendingRotations: deprecated("clearPendingRotations"),
342
- mapDid: deprecated("mapDid"),
343
- clearDidMap: deprecated("clearDidMap"),
344
- clearDidDocs: deprecated("clearDidDocs"),
345
- storeDidDoc: deprecated("storeDidDoc"),
346
- addLabelsToChannel: deprecated("addLabelsToChannel"),
349
+ relocateWebvhAfterMove: krl.Function(["options"], async function (
350
+ options: Record<string, unknown> = {}
351
+ ) {
352
+ const opts: {
353
+ baseUrl?: string;
354
+ renewIngress?: boolean;
355
+ } = {};
356
+ if (typeof options.baseUrl === "string") {
357
+ opts.baseUrl = options.baseUrl;
358
+ }
359
+ if (options.renewIngress === true) {
360
+ opts.renewIngress = true;
361
+ }
362
+ return identity.relocateWebvhAfterMove(this.rsCtx.pico().id, opts);
363
+ }),
364
+
365
+ notifyPeersOfWebvhRotation: krl.Function(["relocation"], async function (
366
+ relocation: Record<string, unknown>
367
+ ) {
368
+ return identity.notifyPeersOfWebvhRotation(
369
+ this.rsCtx.pico().id,
370
+ relocation as unknown as Parameters<
371
+ IdentityService["notifyPeersOfWebvhRotation"]
372
+ >[1]
373
+ );
374
+ }),
375
+
376
+ completePortableMove: krl.Function(["options"], async function (
377
+ options: Record<string, unknown> = {}
378
+ ) {
379
+ const opts: {
380
+ baseUrl?: string;
381
+ renewIngress?: boolean;
382
+ } = {};
383
+ if (typeof options.baseUrl === "string") {
384
+ opts.baseUrl = options.baseUrl;
385
+ }
386
+ if (options.renewIngress === true) {
387
+ opts.renewIngress = true;
388
+ }
389
+ return identity.completePortableMove(this.rsCtx.pico().id, opts);
390
+ }),
391
+
392
+ exportPortableSubtree: krl.Function(
393
+ ["subtreeRootPicoId", "secret"],
394
+ async function (subtreeRootPicoId: string, secret: string) {
395
+ return identity.exportPortableSubtree(
396
+ this.rsCtx.pico().id,
397
+ subtreeRootPicoId,
398
+ secret
399
+ );
400
+ }
401
+ ),
402
+
403
+ summarizePortableSubtreeExport: krl.Function(
404
+ ["blob", "secret"],
405
+ function (blob: string, secret: string) {
406
+ return identity.summarizePortableSubtreeExport(blob, secret);
407
+ }
408
+ ),
409
+
410
+ importPortableSubtree: krl.Function(
411
+ ["blob", "secret", "options"],
412
+ async function (
413
+ blob: string,
414
+ secret: string,
415
+ options: Record<string, unknown> = {}
416
+ ) {
417
+ const opts: RelocateWebvhOptions = {};
418
+ if (typeof options.baseUrl === "string") {
419
+ opts.baseUrl = options.baseUrl;
420
+ }
421
+ if (options.renewIngress === true) {
422
+ opts.renewIngress = true;
423
+ }
424
+ if (Object.keys(opts).length === 0) {
425
+ opts.renewIngress = true;
426
+ }
427
+ const importOpts: SubtreeImportOptions = {};
428
+ if (typeof options.parentChannelEci === "string") {
429
+ importOpts.parentChannelEci = options.parentChannelEci;
430
+ }
431
+ if (typeof options.bootstrapDisplayName === "string") {
432
+ let name = options.bootstrapDisplayName.trim();
433
+ if (
434
+ name.length >= 2 &&
435
+ name.startsWith('"') &&
436
+ name.endsWith('"')
437
+ ) {
438
+ name = name.slice(1, -1).trim();
439
+ }
440
+ if (name.length > 0) {
441
+ importOpts.bootstrapDisplayName = name;
442
+ }
443
+ }
444
+ return identity.importPortableSubtree(
445
+ this.rsCtx.pico().id,
446
+ blob,
447
+ secret,
448
+ opts,
449
+ importOpts
450
+ );
451
+ }
452
+ ),
453
+
454
+ finalizePortableImport: krl.Function(
455
+ ["importResult", "options"],
456
+ async function (
457
+ importResult: SubtreeImportResult,
458
+ options: Record<string, unknown> = {}
459
+ ) {
460
+ const opts: RelocateWebvhOptions = {};
461
+ if (typeof options.baseUrl === "string") {
462
+ opts.baseUrl = options.baseUrl;
463
+ }
464
+ if (options.renewIngress === true) {
465
+ opts.renewIngress = true;
466
+ }
467
+ if (Object.keys(opts).length === 0) {
468
+ opts.renewIngress = true;
469
+ }
470
+ return identity.finalizePortableImport(importResult, opts);
471
+ }
472
+ ),
347
473
  };
348
474
 
349
475
  return module;
350
476
  }
351
477
 
352
- function deprecated(name: string) {
353
- return krl.Function([], async function () {
354
- throw new IdentityError(
355
- `dido:${name} removed in Layer 2 reboot — use engine identity primitives`,
356
- 410
357
- );
358
- });
359
- }
360
-
361
478
  function extractDidcommEndpoint(doc: Record<string, unknown>): string {
362
479
  const services = doc.service as Array<Record<string, unknown>> | undefined;
363
480
  if (!services || services.length === 0) {
@@ -104,7 +104,7 @@ export async function establishSubscriptionIdentity(
104
104
  }
105
105
 
106
106
  export interface LinkRemotePeerInput {
107
- remotePeerDid: string;
107
+ remotePeerDid?: string;
108
108
  remoteWebvhDid?: string;
109
109
  remoteMeshRootId?: string;
110
110
  remoteTxHost?: string;
@@ -123,7 +123,7 @@ export async function linkRemotePeer(
123
123
  }
124
124
  const updated: PeerSubscriptionRecord = {
125
125
  ...sub,
126
- remotePeerDid: input.remotePeerDid,
126
+ remotePeerDid: input.remotePeerDid ?? sub.remotePeerDid,
127
127
  remoteWebvhDid: input.remoteWebvhDid ?? sub.remoteWebvhDid,
128
128
  remoteMeshRootId: input.remoteMeshRootId ?? sub.remoteMeshRootId,
129
129
  remoteTxHost: input.remoteTxHost ?? sub.remoteTxHost,
@@ -0,0 +1,153 @@
1
+ /**
2
+ * Identity snapshots for portable subtree export/import (Phase D).
3
+ */
4
+
5
+ import { PicoFramework } from "pico-framework";
6
+ import type { SubtreePortableHooks } from "pico-engine-core";
7
+ import { IdentityStore } from "./store";
8
+ import type {
9
+ DidCommRoutes,
10
+ PeerSubscriptionRecord,
11
+ WebvhKeys,
12
+ WebvhLogEntry,
13
+ } from "./types";
14
+ import { IdentityError } from "./errors";
15
+ import { meshRootIdFor, webvhPathsForPico } from "./webvh";
16
+ import { warmPeerDidsForPico } from "./veramoDidComm";
17
+
18
+ export interface PortableIdentityExport {
19
+ webvhDid: string;
20
+ webvhLog: WebvhLogEntry[];
21
+ webvhKeys: WebvhKeys;
22
+ webvhWebDoc?: Record<string, unknown>;
23
+ publicIntro: boolean;
24
+ peerSubscriptions: PeerSubscriptionRecord[];
25
+ routes?: DidCommRoutes;
26
+ }
27
+
28
+ function rewritePicoIdInValue<T>(value: T, oldPicoId: string, newPicoId: string): T {
29
+ if (typeof value === "string") {
30
+ return value
31
+ .split(oldPicoId)
32
+ .join(newPicoId) as unknown as T;
33
+ }
34
+ if (Array.isArray(value)) {
35
+ return value.map((item) =>
36
+ rewritePicoIdInValue(item, oldPicoId, newPicoId)
37
+ ) as unknown as T;
38
+ }
39
+ if (value && typeof value === "object") {
40
+ const out: Record<string, unknown> = {};
41
+ for (const [key, child] of Object.entries(value)) {
42
+ out[key] = rewritePicoIdInValue(child, oldPicoId, newPicoId);
43
+ }
44
+ return out as T;
45
+ }
46
+ return value;
47
+ }
48
+
49
+ export function rewriteWebvhLogForPicoId(
50
+ log: WebvhLogEntry[],
51
+ oldPicoId: string,
52
+ newPicoId: string
53
+ ): WebvhLogEntry[] {
54
+ return rewritePicoIdInValue(log, oldPicoId, newPicoId);
55
+ }
56
+
57
+ export async function exportNodeIdentity(
58
+ store: IdentityStore,
59
+ picoId: string
60
+ ): Promise<PortableIdentityExport | null> {
61
+ const webvhDid = await store.getWebvhDid(picoId);
62
+ const webvhLog = await store.getWebvhLog(picoId);
63
+ const webvhKeys = await store.getWebvhKeys(picoId);
64
+ if (!webvhDid || !webvhLog?.length || !webvhKeys) {
65
+ return null;
66
+ }
67
+
68
+ return {
69
+ webvhDid,
70
+ webvhLog,
71
+ webvhKeys,
72
+ webvhWebDoc: (await store.getWebvhWebDoc(picoId)) || undefined,
73
+ publicIntro: (await store.getPublicIntro(picoId)) === true,
74
+ peerSubscriptions: await store.listPeerSubscriptions(picoId),
75
+ routes: (await store.getRoutes(picoId)) || undefined,
76
+ };
77
+ }
78
+
79
+ export async function importNodeIdentity(
80
+ store: IdentityStore,
81
+ pf: PicoFramework,
82
+ oldPicoId: string,
83
+ newPicoId: string,
84
+ raw: unknown,
85
+ eciMap: Record<string, string>,
86
+ picoIdMap: Record<string, string>
87
+ ): Promise<void> {
88
+ if (!raw || typeof raw !== "object") {
89
+ throw new IdentityError("Invalid portable identity export", 400);
90
+ }
91
+ const identity = raw as PortableIdentityExport;
92
+ if (
93
+ typeof identity.webvhDid !== "string" ||
94
+ !Array.isArray(identity.webvhLog) ||
95
+ !identity.webvhKeys
96
+ ) {
97
+ throw new IdentityError("Portable identity export missing webvh fields", 400);
98
+ }
99
+
100
+ const meshRootId = meshRootIdFor(pf, newPicoId);
101
+
102
+ await store.putWebvhKeys(newPicoId, identity.webvhKeys);
103
+ await store.putWebvhLog(newPicoId, identity.webvhLog);
104
+ await store.putWebvhDid(newPicoId, identity.webvhDid);
105
+ await store.putMeshRootId(newPicoId, meshRootId);
106
+ await store.putPublicIntro(newPicoId, identity.publicIntro === true);
107
+ await store.putDidcommIngressEci(newPicoId, "");
108
+ if (identity.webvhWebDoc) {
109
+ await store.putWebvhWebDoc(newPicoId, identity.webvhWebDoc);
110
+ }
111
+
112
+ if (identity.routes) {
113
+ await store.putRoutes(newPicoId, identity.routes);
114
+ }
115
+
116
+ for (const sub of identity.peerSubscriptions || []) {
117
+ const rxEci = sub.rxEci ? eciMap[sub.rxEci] || sub.rxEci : sub.rxEci;
118
+ const remoteMeshRootId =
119
+ sub.remoteMeshRootId && picoIdMap[sub.remoteMeshRootId]
120
+ ? picoIdMap[sub.remoteMeshRootId]
121
+ : sub.remoteMeshRootId;
122
+ await store.putPeerSubscription(newPicoId, {
123
+ ...sub,
124
+ rxEci,
125
+ remoteMeshRootId,
126
+ });
127
+ }
128
+
129
+ await warmPeerDidsForPico(store, newPicoId);
130
+
131
+ if (webvhPathsForPico(newPicoId)[1] !== newPicoId) {
132
+ throw new IdentityError("Webvh path rewrite failed after import", 500);
133
+ }
134
+ }
135
+
136
+ export function createSubtreePortableHooks(
137
+ store: IdentityStore,
138
+ pf: PicoFramework
139
+ ): SubtreePortableHooks {
140
+ return {
141
+ exportNodeIdentity: (picoId) => exportNodeIdentity(store, picoId),
142
+ importNodeIdentity: (oldPicoId, newPicoId, identity, eciMap, picoIdMap) =>
143
+ importNodeIdentity(
144
+ store,
145
+ pf,
146
+ oldPicoId,
147
+ newPicoId,
148
+ identity,
149
+ eciMap,
150
+ picoIdMap
151
+ ),
152
+ };
153
+ }
@@ -7,6 +7,20 @@ export {
7
7
  export { IdentityService, type IdentityServiceDeps } from "./IdentityService";
8
8
  export { IdentityError } from "./errors";
9
9
  export { default as initDidoModule } from "./didoModule";
10
+ export {
11
+ createSubtreePortableHooks,
12
+ exportNodeIdentity,
13
+ importNodeIdentity,
14
+ rewriteWebvhLogForPicoId,
15
+ type PortableIdentityExport,
16
+ } from "./identityPortable";
17
+ export {
18
+ exportPortableSubtree,
19
+ importPortableSubtree,
20
+ finalizePortableImport,
21
+ type PortableMoveDeps,
22
+ type PortableMoveImportResult,
23
+ } from "./portableMove";
10
24
  export {
11
25
  IDENTITY_STORAGE_KNOWN_GAP,
12
26
  type CachedDidDoc,