pico-engine 1.6.4 → 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 (98) hide show
  1. package/README.md +13 -8
  2. package/dist/RulesetRegistryLoaderFs.js +14 -2
  3. package/dist/auth/cookies.js +32 -0
  4. package/dist/auth/index.js +6 -1
  5. package/dist/channelIdentityPolicy.js +22 -0
  6. package/dist/cli.js +104 -69
  7. package/dist/engineConfig.js +280 -0
  8. package/dist/identity/IdentityService.js +90 -0
  9. package/dist/identity/crossPico.js +24 -8
  10. package/dist/identity/didoModule.js +80 -18
  11. package/dist/identity/establishSubscription.js +2 -2
  12. package/dist/identity/identityPortable.js +92 -0
  13. package/dist/identity/index.js +10 -1
  14. package/dist/identity/localPeerReconcile.js +65 -0
  15. package/dist/identity/peerDid4.js +175 -0
  16. package/dist/identity/peerDid4Create.js +90 -0
  17. package/dist/identity/portableExportPrepare.js +196 -0
  18. package/dist/identity/portableMove.js +87 -0
  19. package/dist/identity/skyIntro.js +6 -3
  20. package/dist/identity/skyProtocol.js +26 -1
  21. package/dist/identity/skyRotation.js +121 -0
  22. package/dist/identity/store.js +5 -1
  23. package/dist/identity/subscriptionEntSync.js +72 -0
  24. package/dist/identity/veramoDidComm.js +41 -2
  25. package/dist/identity/webvh.js +4 -2
  26. package/dist/identity/webvhRelocation.js +115 -0
  27. package/dist/index.js +82 -22
  28. package/dist/logging.js +8 -12
  29. package/dist/oauth/OAuthService.js +6 -2
  30. package/dist/policyConfigFromJson.js +112 -0
  31. package/dist/runMcp.js +27 -0
  32. package/dist/server.js +56 -24
  33. package/dist/subtreeWrangler.js +180 -0
  34. package/dist/uiChannelPolicies.js +15 -0
  35. package/krl/io.picolabs.oauth.krl +41 -2
  36. package/krl/io.picolabs.pds.krl +131 -10
  37. package/krl/io.picolabs.pico-engine-ui.krl +209 -21
  38. package/krl/io.picolabs.portable_subtree.krl +97 -0
  39. package/krl/io.picolabs.subscription.krl +180 -72
  40. package/krl/io.picolabs.wrangler.krl +296 -57
  41. package/mcp/devResources.js +118 -0
  42. package/mcp/devTools.js +351 -0
  43. package/mcp/engineClient.js +133 -0
  44. package/mcp/meshHttp.js +137 -0
  45. package/mcp/meshTools.js +189 -0
  46. package/mcp/runStdio.js +34 -0
  47. package/mcp/schemaToZod.js +56 -0
  48. package/package.json +20 -8
  49. package/public/docs/_sidebar.md +2 -1
  50. package/public/docs/llms-full.txt +479 -0
  51. package/public/docs/llms.txt +37 -0
  52. package/public/docs/openapi.yaml +78 -0
  53. package/public/docs/pico-engine.md +235 -4
  54. package/public/docs/pico-overview.md +117 -0
  55. package/public/docs/pico.md +3 -1
  56. package/public/docs/rulesets/README.md +25 -0
  57. package/public/docs/rulesets/io.picolabs.oauth.md +71 -0
  58. package/public/docs/rulesets/io.picolabs.pds.md +327 -0
  59. package/public/docs/rulesets/io.picolabs.pico-engine-ui.md +65 -0
  60. package/public/docs/rulesets/io.picolabs.portable_subtree.md +94 -0
  61. package/public/docs/rulesets/io.picolabs.subscription.md +398 -0
  62. package/public/docs/rulesets/io.picolabs.wrangler.md +471 -0
  63. package/public/pico-engine-ui.css +1 -1
  64. package/public/pico-engine-ui.js +28 -26
  65. package/src/RulesetRegistryLoaderFs.ts +18 -3
  66. package/src/auth/cookies.ts +34 -0
  67. package/src/auth/index.ts +7 -0
  68. package/src/channelIdentityPolicy.ts +29 -0
  69. package/src/cli.ts +68 -37
  70. package/src/engineConfig.ts +345 -0
  71. package/src/identity/IdentityService.ts +189 -1
  72. package/src/identity/crossPico.ts +57 -8
  73. package/src/identity/didoModule.ts +140 -23
  74. package/src/identity/establishSubscription.ts +2 -2
  75. package/src/identity/identityPortable.ts +153 -0
  76. package/src/identity/index.ts +14 -0
  77. package/src/identity/localPeerReconcile.ts +97 -0
  78. package/src/identity/peerDid4.ts +197 -0
  79. package/src/identity/peerDid4Create.ts +121 -0
  80. package/src/identity/portableExportPrepare.ts +302 -0
  81. package/src/identity/portableMove.ts +193 -0
  82. package/src/identity/skyIntro.ts +11 -11
  83. package/src/identity/skyProtocol.ts +46 -0
  84. package/src/identity/skyRotation.ts +211 -0
  85. package/src/identity/store.ts +5 -1
  86. package/src/identity/subscriptionEntSync.ts +97 -0
  87. package/src/identity/veramoDidComm.ts +52 -2
  88. package/src/identity/webvh.ts +4 -4
  89. package/src/identity/webvhRelocation.ts +167 -0
  90. package/src/index.ts +119 -25
  91. package/src/logging.ts +8 -14
  92. package/src/oauth/OAuthService.ts +11 -3
  93. package/src/policyConfigFromJson.ts +131 -0
  94. package/src/runMcp.ts +30 -0
  95. package/src/server.ts +79 -26
  96. package/src/subtreeWrangler.ts +278 -0
  97. package/src/uiChannelPolicies.ts +15 -0
  98. package/krl/io.picolabs.did-o.krl +0 -349
@@ -0,0 +1,211 @@
1
+ /**
2
+ * DIDComm SKY rotation notices for portable did:webvh move (Phase D).
3
+ */
4
+
5
+ import fetch from "cross-fetch";
6
+ import { Pico, PicoFramework } from "pico-framework";
7
+ import { IdentityStore } from "./store";
8
+ import type { DidCommPlainMessage, IdentityService } from "./IdentityService";
9
+ import { IdentityError } from "./errors";
10
+ import { linkRemotePeer } from "./establishSubscription";
11
+ import { extractDidcommEndpoint } from "./crossPico";
12
+ import {
13
+ SKY_ROTATE,
14
+ parseSkyRotateBody,
15
+ skyRotateToWranglerAttrs,
16
+ type SkyRotateBody,
17
+ } from "./skyProtocol";
18
+ import { packDidCommMessage } from "./veramoDidComm";
19
+ import type { RelocateWebvhResult } from "./webvhRelocation";
20
+ import type { PendingRotation } from "./types";
21
+
22
+ export interface SkyRotationDeps {
23
+ store: IdentityStore;
24
+ pf: PicoFramework;
25
+ getBaseUrl: () => string;
26
+ identity: IdentityService;
27
+ }
28
+
29
+ function findPico(pf: PicoFramework, picoId: string): Pico | undefined {
30
+ return pf.loadedPicos().find((p) => p.id === picoId);
31
+ }
32
+
33
+ async function resolveDidcommEndpointForDid(
34
+ identity: IdentityService,
35
+ did: string,
36
+ remoteDidcommEndpoint?: string
37
+ ): Promise<string> {
38
+ if (remoteDidcommEndpoint) {
39
+ return remoteDidcommEndpoint;
40
+ }
41
+ const doc = await identity.resolveDid("", did);
42
+ return extractDidcommEndpoint(doc);
43
+ }
44
+
45
+ async function postJwe(endpoint: string, jwe: string): Promise<void> {
46
+ const res = await fetch(endpoint, {
47
+ method: "POST",
48
+ headers: { "Content-Type": "application/didcomm-encrypted+json" },
49
+ body: jwe,
50
+ });
51
+ if (!res.ok) {
52
+ const detail = await res.text();
53
+ throw new IdentityError(
54
+ `DIDComm POST failed: HTTP ${res.status} ${detail}`,
55
+ res.status
56
+ );
57
+ }
58
+ }
59
+
60
+ async function deliverRotateNotice(
61
+ deps: SkyRotationDeps,
62
+ fromPicoId: string,
63
+ toPeerDid: string,
64
+ remoteWebvhDid: string | undefined,
65
+ remoteDidcommEndpoint: string | undefined,
66
+ body: SkyRotateBody,
67
+ fromPrior?: string
68
+ ): Promise<void> {
69
+ const fromWebvh = await deps.store.getWebvhDid(fromPicoId);
70
+ const sub = (await deps.store.listPeerSubscriptions(fromPicoId)).find(
71
+ (s) => s.remotePeerDid === toPeerDid || s.remoteDid === toPeerDid
72
+ );
73
+ const fromPeer = sub?.peerDid;
74
+ if (!fromPeer) {
75
+ throw new IdentityError(
76
+ `No local peer DID for subscription to ${toPeerDid}`,
77
+ 404
78
+ );
79
+ }
80
+
81
+ const message: DidCommPlainMessage = {
82
+ id: `rotate-${Date.now()}`,
83
+ typ: "application/didcomm-plain+json",
84
+ type: SKY_ROTATE,
85
+ from: fromPeer,
86
+ to: [toPeerDid],
87
+ body,
88
+ created_time: Math.floor(Date.now() / 1000),
89
+ ...(fromPrior ? { from_prior: fromPrior } : {}),
90
+ };
91
+
92
+ const packed = await packDidCommMessage(
93
+ fromPicoId,
94
+ message,
95
+ fromPeer,
96
+ toPeerDid,
97
+ deps.store,
98
+ { resolveDid: (did) => deps.identity.resolveDid("", did) }
99
+ );
100
+
101
+ const endpoint = await resolveDidcommEndpointForDid(
102
+ deps.identity,
103
+ remoteWebvhDid || toPeerDid,
104
+ remoteDidcommEndpoint
105
+ );
106
+ await postJwe(endpoint, packed);
107
+ }
108
+
109
+ /** Notify established peers that this pico's did:webvh location changed. */
110
+ export async function notifyPeersOfWebvhRotation(
111
+ deps: SkyRotationDeps,
112
+ picoId: string,
113
+ relocation: RelocateWebvhResult
114
+ ): Promise<number> {
115
+ const baseUrl = deps.getBaseUrl().replace(/\/$/, "");
116
+ const body: SkyRotateBody = {
117
+ sky_version: "1.0",
118
+ prior_webvh_did: relocation.priorDid,
119
+ new_webvh_did: relocation.newDid,
120
+ new_tx_host: baseUrl,
121
+ new_didcomm_endpoint: relocation.didcommEndpoint,
122
+ };
123
+
124
+ const subs = await deps.store.listPeerSubscriptions(picoId);
125
+ let sent = 0;
126
+ for (const sub of subs) {
127
+ const remotePeer = sub.remotePeerDid || sub.remoteDid;
128
+ if (!remotePeer) {
129
+ continue;
130
+ }
131
+ try {
132
+ await deliverRotateNotice(
133
+ deps,
134
+ picoId,
135
+ remotePeer,
136
+ sub.remoteWebvhDid,
137
+ sub.remoteDidcommEndpoint,
138
+ body,
139
+ relocation.priorDid !== relocation.newDid ? relocation.priorDid : undefined
140
+ );
141
+ sent += 1;
142
+ } catch (err) {
143
+ const msg = err instanceof Error ? err.message : String(err);
144
+ console.warn(
145
+ `[portable-move] SKY rotate to ${remotePeer} failed (import continues): ${msg}`
146
+ );
147
+ }
148
+ }
149
+ return sent;
150
+ }
151
+
152
+ /** Apply a SKY rotate message on the recipient pico. */
153
+ export async function handleSkyRotateAtIngress(
154
+ deps: SkyRotationDeps,
155
+ recipientPicoId: string,
156
+ message: DidCommPlainMessage
157
+ ): Promise<Record<string, unknown>> {
158
+ const senderDid = message.from;
159
+ if (!senderDid) {
160
+ throw new IdentityError("SKY rotate missing from", 400);
161
+ }
162
+
163
+ const rotate = parseSkyRotateBody(message.body);
164
+ const sub = await deps.store.findPeerSubscriptionBySenderDid(
165
+ recipientPicoId,
166
+ senderDid
167
+ );
168
+ if (!sub) {
169
+ throw new IdentityError("unknown_subscription", 404);
170
+ }
171
+
172
+ await linkRemotePeer(deps.store, recipientPicoId, sub.subscriptionId, {
173
+ remotePeerDid: senderDid,
174
+ remoteWebvhDid: rotate.new_webvh_did,
175
+ remoteTxHost: rotate.new_tx_host,
176
+ remoteDidcommEndpoint: rotate.new_didcomm_endpoint,
177
+ });
178
+
179
+ const pending: PendingRotation[] =
180
+ (await deps.store.getPendingRotations(recipientPicoId)) || [];
181
+ pending.push({
182
+ priorDid: rotate.prior_webvh_did,
183
+ newDid: rotate.new_webvh_did,
184
+ peerDid: senderDid,
185
+ subscriptionId: sub.subscriptionId,
186
+ receivedAt: new Date().toISOString(),
187
+ });
188
+ await deps.store.putPendingRotations(recipientPicoId, pending);
189
+
190
+ const pico = findPico(deps.pf, recipientPicoId);
191
+ if (pico) {
192
+ await pico.event({
193
+ eci: pico.id,
194
+ domain: "wrangler",
195
+ name: "webvh_peer_rotated",
196
+ data: {
197
+ attrs: skyRotateToWranglerAttrs(rotate, {
198
+ Id: sub.subscriptionId,
199
+ peer_did: senderDid,
200
+ }),
201
+ },
202
+ time: Date.now(),
203
+ });
204
+ }
205
+
206
+ return {
207
+ status: "ok",
208
+ subscriptionId: sub.subscriptionId,
209
+ new_webvh_did: rotate.new_webvh_did,
210
+ };
211
+ }
@@ -1,5 +1,6 @@
1
1
  import { PicoDb, PicoDbKey } from "pico-framework";
2
2
  import { dbDel, dbGet, dbList, dbPut } from "./dbHelpers";
3
+ import { peerDid4Matches } from "./peerDid4";
3
4
  import {
4
5
  CachedDidDoc,
5
6
  DidCommRoutes,
@@ -321,11 +322,14 @@ export async function migrateFromDidO(_picoId: string): Promise<void> {
321
322
  return;
322
323
  }
323
324
 
324
- /** Match did:peer short/long forms (numalgo 0/2). */
325
+ /** Match did:peer short/long forms (numalgo 0/2/4). */
325
326
  function peerDidMatches(stored: string, incoming: string): boolean {
326
327
  if (stored === incoming) {
327
328
  return true;
328
329
  }
330
+ if (stored.startsWith("did:peer:4") || incoming.startsWith("did:peer:4")) {
331
+ return peerDid4Matches(stored, incoming);
332
+ }
329
333
  const storedShort = peerDidShortForm(stored);
330
334
  const incomingShort = peerDidShortForm(incoming);
331
335
  return storedShort.length > 0 && storedShort === incomingShort;
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Keep wrangler subscription ent buses aligned with engine identity store after import.
3
+ */
4
+
5
+ import { Pico, PicoFramework } from "pico-framework";
6
+ import { IdentityStore } from "./store";
7
+ import type { PeerSubscriptionRecord } from "./types";
8
+
9
+ const SUBSCRIPTION_RID = "io.picolabs.subscription";
10
+
11
+ function busId(bus: Record<string, unknown>): string | undefined {
12
+ const id = bus["Id"];
13
+ return typeof id === "string" ? id : undefined;
14
+ }
15
+
16
+ function mergeIdentityIntoBus(
17
+ bus: Record<string, unknown>,
18
+ rec: PeerSubscriptionRecord
19
+ ): Record<string, unknown> {
20
+ const out: Record<string, unknown> = { ...bus, layer2: true };
21
+ if (rec.rxEci) {
22
+ out["Rx"] = rec.rxEci;
23
+ }
24
+ if (rec.peerDid) {
25
+ out["Rx_did"] = rec.peerDid;
26
+ }
27
+ if (rec.remotePeerDid || rec.remoteDid) {
28
+ out["Tx_did"] =
29
+ out["Tx_did"] || rec.remoteWebvhDid || rec.remotePeerDid || rec.remoteDid;
30
+ }
31
+ if (rec.remoteWebvhDid) {
32
+ out["Tx_did"] = rec.remoteWebvhDid;
33
+ }
34
+ if (rec.remoteTxHost) {
35
+ out["Tx_host"] = rec.remoteTxHost;
36
+ }
37
+ return out;
38
+ }
39
+
40
+ function findBusInPools(
41
+ id: string,
42
+ pools: Record<string, unknown>[]
43
+ ): Record<string, unknown> | undefined {
44
+ return pools.find((b) => busId(b) === id);
45
+ }
46
+
47
+ /** Merge identity peer subscriptions into ent:established (Layer 2 DID relationships). */
48
+ export async function syncLayer2EstablishedFromIdentity(
49
+ store: IdentityStore,
50
+ pf: PicoFramework,
51
+ picoId: string
52
+ ): Promise<void> {
53
+ const pico = pf.getPico(picoId);
54
+ if (!pico?.rulesets[SUBSCRIPTION_RID]) {
55
+ return;
56
+ }
57
+
58
+ const peerSubs = await store.listPeerSubscriptions(picoId);
59
+ if (peerSubs.length === 0) {
60
+ return;
61
+ }
62
+
63
+ const establishedRaw = await pico.getEnt(SUBSCRIPTION_RID, "established");
64
+ let list: Record<string, unknown>[] = Array.isArray(establishedRaw)
65
+ ? establishedRaw.map((b) =>
66
+ b && typeof b === "object" ? { ...(b as Record<string, unknown>) } : {}
67
+ )
68
+ : [];
69
+
70
+ const inbound = await pico.getEnt(SUBSCRIPTION_RID, "inbound");
71
+ const outbound = await pico.getEnt(SUBSCRIPTION_RID, "outbound");
72
+ const pools: Record<string, unknown>[] = [
73
+ ...(Array.isArray(inbound)
74
+ ? inbound.filter((b) => b && typeof b === "object") as Record<string, unknown>[]
75
+ : []),
76
+ ...(Array.isArray(outbound)
77
+ ? outbound.filter((b) => b && typeof b === "object") as Record<string, unknown>[]
78
+ : []),
79
+ ];
80
+
81
+ for (const rec of peerSubs) {
82
+ const id = rec.subscriptionId;
83
+ let idx = list.findIndex((b) => busId(b) === id);
84
+ if (idx >= 0) {
85
+ list[idx] = mergeIdentityIntoBus(list[idx], rec);
86
+ continue;
87
+ }
88
+ const fromPool = findBusInPools(id, pools);
89
+ if (fromPool || rec.remotePeerDid || rec.remoteWebvhDid) {
90
+ list.push(
91
+ mergeIdentityIntoBus(fromPool || { Id: id }, rec)
92
+ );
93
+ }
94
+ }
95
+
96
+ await pico.putEnt(SUBSCRIPTION_RID, "established", list);
97
+ }
@@ -6,6 +6,8 @@ import {
6
6
  type StoredPeerDidBundle,
7
7
  type StoredVeramoKey,
8
8
  } from "./peerDid";
9
+ import { isPeerDid4, resolvePeerDid4 } from "./peerDid4";
10
+ import { createPeerDid4WithKeys } from "./peerDid4Create";
9
11
  import {
10
12
  storedKeysFromWebvhKeys,
11
13
  webvhAgreementKeysForVeramo,
@@ -105,6 +107,40 @@ async function createAgentBundle(): Promise<AgentBundle> {
105
107
  const { PeerDIDProvider, getResolver: getPeerResolver } = require("@veramo/did-provider-peer");
106
108
  const { Resolver } = require("did-resolver");
107
109
 
110
+ const basePeerResolver = getPeerResolver();
111
+ const peerResolver = {
112
+ ...basePeerResolver,
113
+ peer: async (
114
+ did: string,
115
+ parsed: unknown,
116
+ resolver: unknown,
117
+ options: unknown
118
+ ) => {
119
+ if (isPeerDid4(did)) {
120
+ try {
121
+ const didDocument = resolvePeerDid4(did);
122
+ return {
123
+ didDocument,
124
+ didDocumentMetadata: {},
125
+ didResolutionMetadata: {
126
+ contentType: "application/did+ld+json",
127
+ },
128
+ };
129
+ } catch (err) {
130
+ return {
131
+ didDocument: null,
132
+ didDocumentMetadata: {},
133
+ didResolutionMetadata: {
134
+ error: "invalidDid",
135
+ message: (err as Error).message,
136
+ },
137
+ };
138
+ }
139
+ }
140
+ return basePeerResolver.peer(did, parsed, resolver, options);
141
+ },
142
+ };
143
+
108
144
  const privateKeyStore = new MemoryPrivateKeyStore();
109
145
  const agent = createAgent({
110
146
  plugins: [
@@ -120,7 +156,7 @@ async function createAgentBundle(): Promise<AgentBundle> {
120
156
  },
121
157
  }),
122
158
  new DIDResolverPlugin({
123
- resolver: new Resolver({ ...getPeerResolver(), ...webvhResolverMethods() }),
159
+ resolver: new Resolver({ ...peerResolver, ...webvhResolverMethods() }),
124
160
  }),
125
161
  new DIDComm(),
126
162
  ],
@@ -149,7 +185,7 @@ export async function exportVeramoKeysForDid(
149
185
  }
150
186
 
151
187
  /** Create a did:peer (num_algo 2) and export key material for persistence. */
152
- export async function createPeerDidWithKeys(): Promise<{
188
+ export async function createPeerDid2WithKeys(): Promise<{
153
189
  did: string;
154
190
  keys: StoredPeerDidBundle;
155
191
  }> {
@@ -165,6 +201,20 @@ export async function createPeerDidWithKeys(): Promise<{
165
201
  };
166
202
  }
167
203
 
204
+ /** Create a did:peer:4 (long form) and export key material for persistence. */
205
+ export async function createPeerDidWithKeys(): Promise<{
206
+ did: string;
207
+ keys: StoredPeerDidBundle;
208
+ }> {
209
+ const created = createPeerDid4WithKeys();
210
+ await getAgentBundle();
211
+ await importPeerDidOnAgent(created.did, created.keys.veramoKeys);
212
+ return {
213
+ did: created.did,
214
+ keys: created.keys,
215
+ };
216
+ }
217
+
168
218
  /** @deprecated Prefer createPeerDidWithKeys — returns DID only. */
169
219
  export async function createPeerDid(): Promise<string> {
170
220
  const { did } = await createPeerDidWithKeys();
@@ -131,9 +131,9 @@ const INGRESS_CHANNEL: ChannelConfig = {
131
131
  },
132
132
  };
133
133
 
134
- async function ensureDidcommIngress(
135
- pf: PicoFramework,
134
+ export async function ensureDidcommIngress(
136
135
  store: IdentityStore,
136
+ pf: PicoFramework,
137
137
  picoId: string,
138
138
  baseUrl: string
139
139
  ): Promise<string> {
@@ -151,7 +151,7 @@ async function ensureDidcommIngress(
151
151
  return eci;
152
152
  }
153
153
 
154
- function didcommServiceEndpoint(baseUrl: string, ingressEci: string): string {
154
+ export function didcommServiceEndpoint(baseUrl: string, ingressEci: string): string {
155
155
  const base = baseUrl.replace(/\/$/, "");
156
156
  return `${base}/sky/event/${ingressEci}/none/dido/didcomm_message`;
157
157
  }
@@ -176,7 +176,7 @@ export async function ensureWebvhDid(
176
176
  const webvh = await loadDidWebvhTs();
177
177
  const keyMaterial = await generateWebvhKeyMaterial();
178
178
  const crypto = await createWebvhCrypto(keyMaterial);
179
- const ingressEci = await ensureDidcommIngress(pf, store, picoId, baseUrl);
179
+ const ingressEci = await ensureDidcommIngress(store, pf, picoId, baseUrl);
180
180
 
181
181
  const result = await webvh.createDID({
182
182
  address: baseUrlToDidAddress(baseUrl),
@@ -0,0 +1,167 @@
1
+ /**
2
+ * did:webvh log update for portable move (Phase D, pico-move).
3
+ */
4
+
5
+ import { PicoFramework } from "pico-framework";
6
+ import { IdentityStore } from "./store";
7
+ import type { WebvhLogEntry } from "./types";
8
+ import { IdentityError } from "./errors";
9
+ import {
10
+ baseUrlToDidAddress,
11
+ didcommServiceEndpoint,
12
+ ensureDidcommIngress,
13
+ keysFromStore,
14
+ resolveLocalWebvhLog,
15
+ webvhPathsForPico,
16
+ } from "./webvh";
17
+ import {
18
+ createPassthroughVerifier,
19
+ createWebvhCrypto,
20
+ loadDidWebvhTs,
21
+ } from "./webvhCrypto";
22
+
23
+ export interface RelocateWebvhOptions {
24
+ /** Override engine base URL (default: running engine base_url). */
25
+ baseUrl?: string;
26
+ /** Override log path segments (default: picos/{picoId}). */
27
+ paths?: string[];
28
+ /** Mint a fresh DIDComm ingress channel (simulates post-import ECIs). */
29
+ renewIngress?: boolean;
30
+ }
31
+
32
+ export interface RelocateWebvhResult {
33
+ priorDid: string;
34
+ newDid: string;
35
+ scid: string;
36
+ didcommEndpoint: string;
37
+ }
38
+
39
+ function scidFromLog(log: WebvhLogEntry[]): string {
40
+ const params = log[0]?.parameters as { scid?: string } | undefined;
41
+ const scid = params?.scid;
42
+ if (typeof scid !== "string" || scid.length === 0) {
43
+ throw new IdentityError("webvh log missing SCID", 500);
44
+ }
45
+ return scid;
46
+ }
47
+
48
+ /** Append a portable log entry for a new host/path or DIDComm endpoint. */
49
+ export async function relocateWebvhDid(
50
+ store: IdentityStore,
51
+ pf: PicoFramework,
52
+ getBaseUrl: () => string,
53
+ picoId: string,
54
+ options: RelocateWebvhOptions = {}
55
+ ): Promise<RelocateWebvhResult> {
56
+ const priorDid = await store.getWebvhDid(picoId);
57
+ const log = await store.getWebvhLog(picoId);
58
+ const rawKeys = await store.getWebvhKeys(picoId);
59
+ if (!priorDid || !log?.length || !rawKeys) {
60
+ throw new IdentityError(`Pico ${picoId} has no did:webvh to relocate`, 404);
61
+ }
62
+
63
+ const keyMaterial = keysFromStore(rawKeys);
64
+ if (!keyMaterial) {
65
+ throw new IdentityError(`Pico ${picoId} webvh keys are invalid`, 500);
66
+ }
67
+
68
+ const baseUrl = options.baseUrl || getBaseUrl();
69
+ if (!baseUrl) {
70
+ throw new IdentityError("Engine base_url is required to relocate did:webvh", 500);
71
+ }
72
+
73
+ const priorScid = scidFromLog(log);
74
+ const crypto = await createWebvhCrypto(keyMaterial);
75
+ const verifier = await createPassthroughVerifier();
76
+
77
+ let ingressEci = await store.getDidcommIngressEci(picoId);
78
+ if (options.renewIngress || !ingressEci) {
79
+ if (options.renewIngress && ingressEci) {
80
+ await store.putDidcommIngressEci(picoId, "");
81
+ }
82
+ ingressEci = await ensureDidcommIngress(store, pf, picoId, baseUrl);
83
+ }
84
+
85
+ const webvh = await loadDidWebvhTs();
86
+ const updated = await webvh.updateDID({
87
+ log: log as any,
88
+ signer: crypto,
89
+ verifier,
90
+ updateKeys: [keyMaterial.updateKeyMultibase],
91
+ verificationMethods: [keyMaterial.verificationMethod],
92
+ address: baseUrlToDidAddress(baseUrl),
93
+ paths: options.paths || webvhPathsForPico(picoId),
94
+ services: [
95
+ {
96
+ id: "#didcomm",
97
+ type: "DIDCommMessaging",
98
+ serviceEndpoint: didcommServiceEndpoint(baseUrl, ingressEci),
99
+ accept: ["didcomm/v2"],
100
+ },
101
+ ],
102
+ });
103
+
104
+ const newDid = updated.did;
105
+ const newScid = updated.meta.scid;
106
+ if (newScid !== priorScid) {
107
+ throw new IdentityError(
108
+ `webvh SCID changed during relocation (${priorScid} → ${newScid})`,
109
+ 500
110
+ );
111
+ }
112
+
113
+ await store.putWebvhDid(picoId, newDid);
114
+ await store.putWebvhLog(picoId, updated.log as unknown as WebvhLogEntry[]);
115
+ if (updated.webDoc) {
116
+ await store.putWebvhWebDoc(picoId, updated.webDoc as Record<string, unknown>);
117
+ }
118
+ await store.putDidDoc(picoId, {
119
+ did: newDid,
120
+ doc: updated.doc as Record<string, unknown>,
121
+ cachedAt: new Date().toISOString(),
122
+ });
123
+
124
+ const endpoint = didcommServiceEndpoint(baseUrl, ingressEci);
125
+ return {
126
+ priorDid,
127
+ newDid,
128
+ scid: newScid,
129
+ didcommEndpoint: endpoint,
130
+ };
131
+ }
132
+
133
+ /** Resolve SCID from a stored log (for tests and verification). */
134
+ export async function webvhScidFromStore(
135
+ store: IdentityStore,
136
+ picoId: string
137
+ ): Promise<string | null> {
138
+ const log = await store.getWebvhLog(picoId);
139
+ if (!log?.length) {
140
+ return null;
141
+ }
142
+ try {
143
+ return scidFromLog(log);
144
+ } catch {
145
+ return null;
146
+ }
147
+ }
148
+
149
+ /** Verify local log resolves and SCID matches expectation. */
150
+ export async function assertWebvhScidUnchanged(
151
+ store: IdentityStore,
152
+ picoId: string,
153
+ expectedScid: string
154
+ ): Promise<void> {
155
+ const log = await store.getWebvhLog(picoId);
156
+ if (!log?.length) {
157
+ throw new IdentityError("Missing webvh log", 404);
158
+ }
159
+ const resolved = await resolveLocalWebvhLog(log);
160
+ const scid = scidFromLog(log);
161
+ if (scid !== expectedScid) {
162
+ throw new IdentityError(`SCID mismatch: ${scid} !== ${expectedScid}`, 500);
163
+ }
164
+ if (resolved.did !== (await store.getWebvhDid(picoId))) {
165
+ throw new IdentityError("Resolved DID does not match stored DID", 500);
166
+ }
167
+ }