pico-engine 1.5.0 → 1.6.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 (62) hide show
  1. package/README.md +41 -0
  2. package/dist/RulesetRegistryLoaderFs.js +2 -0
  3. package/dist/auth/AuthService.js +77 -13
  4. package/dist/bundledKrl.js +42 -0
  5. package/dist/identity/IdentityService.js +340 -0
  6. package/dist/identity/crossPico.js +238 -0
  7. package/dist/identity/dbHelpers.js +67 -0
  8. package/dist/identity/didcommIngressRoutes.js +44 -0
  9. package/dist/identity/didoModule.js +252 -0
  10. package/dist/identity/errors.js +11 -0
  11. package/dist/identity/establishSubscription.js +97 -0
  12. package/dist/identity/index.js +15 -0
  13. package/dist/identity/peerDid.js +9 -0
  14. package/dist/identity/skyIntro.js +194 -0
  15. package/dist/identity/skyProtocol.js +105 -0
  16. package/dist/identity/store.js +233 -0
  17. package/dist/identity/types.js +13 -0
  18. package/dist/identity/veramoDidComm.js +260 -0
  19. package/dist/identity/webvh.js +266 -0
  20. package/dist/identity/webvhCrypto.js +128 -0
  21. package/dist/identity/webvhRoutes.js +61 -0
  22. package/dist/index.js +26 -2
  23. package/dist/oauth/OAuthService.js +32 -0
  24. package/dist/provisionRoot.js +56 -18
  25. package/dist/server.js +52 -1
  26. package/dist/uiChannelPolicies.js +48 -0
  27. package/krl/io.picolabs.did-o.krl +5 -1
  28. package/krl/io.picolabs.pico-engine-ui.krl +106 -18
  29. package/krl/io.picolabs.subscription.krl +242 -23
  30. package/krl/io.picolabs.wrangler.krl +221 -12
  31. package/package.json +29 -6
  32. package/public/docs/krl/_sidebar.md +1 -0
  33. package/public/docs/krl/discovery.md +144 -0
  34. package/public/docs/krl/modules/ctx.md +8 -0
  35. package/public/docs/krl/modules/event.md +41 -0
  36. package/public/pico-engine-ui.css +1 -1
  37. package/public/pico-engine-ui.js +21 -18
  38. package/src/RulesetRegistryLoaderFs.ts +2 -0
  39. package/src/auth/AuthService.ts +109 -14
  40. package/src/bundledKrl.ts +42 -0
  41. package/src/identity/IdentityService.ts +571 -0
  42. package/src/identity/crossPico.ts +371 -0
  43. package/src/identity/dbHelpers.ts +51 -0
  44. package/src/identity/didcommIngressRoutes.ts +54 -0
  45. package/src/identity/didoModule.ts +388 -0
  46. package/src/identity/errors.ts +8 -0
  47. package/src/identity/establishSubscription.ts +160 -0
  48. package/src/identity/index.ts +24 -0
  49. package/src/identity/peerDid.ts +22 -0
  50. package/src/identity/skyIntro.ts +321 -0
  51. package/src/identity/skyProtocol.ts +192 -0
  52. package/src/identity/store.ts +343 -0
  53. package/src/identity/types.ts +63 -0
  54. package/src/identity/veramoDidComm.ts +363 -0
  55. package/src/identity/webvh.ts +325 -0
  56. package/src/identity/webvhCrypto.ts +200 -0
  57. package/src/identity/webvhRoutes.ts +64 -0
  58. package/src/index.ts +31 -2
  59. package/src/oauth/OAuthService.ts +36 -0
  60. package/src/provisionRoot.ts +75 -21
  61. package/src/server.ts +58 -1
  62. package/src/uiChannelPolicies.ts +49 -0
@@ -0,0 +1,363 @@
1
+ import { IdentityStore } from "./store";
2
+ import type { DidCommPlainMessage } from "./IdentityService";
3
+ import { IdentityError } from "./errors";
4
+ import {
5
+ peerKeysFromRecord,
6
+ type StoredPeerDidBundle,
7
+ type StoredVeramoKey,
8
+ } from "./peerDid";
9
+ import {
10
+ storedKeysFromWebvhKeys,
11
+ webvhAgreementKeysForVeramo,
12
+ } from "./webvhCrypto";
13
+ import { resolveLocalWebvhLog } from "./webvh";
14
+
15
+ type VeramoAgent = {
16
+ didManagerGet: (args: { did: string }) => Promise<unknown>;
17
+ didManagerCreate: (args: {
18
+ provider: string;
19
+ options?: { num_algo?: number };
20
+ }) => Promise<{ did: string; keys: Array<{ kid: string; publicKeyHex: string; meta?: Record<string, unknown> }> }>;
21
+ didManagerImport: (args: {
22
+ did: string;
23
+ provider: string;
24
+ keys: StoredVeramoKey[];
25
+ services: unknown[];
26
+ }) => Promise<boolean>;
27
+ packDIDCommMessage: (args: {
28
+ message: DidCommPlainMessage;
29
+ from: string;
30
+ to: string[];
31
+ packing: "authcrypt";
32
+ }) => Promise<{ message: string }>;
33
+ unpackDIDCommMessage: (args: {
34
+ message: string;
35
+ }) => Promise<{ message: DidCommPlainMessage; metaData?: Record<string, unknown> }>;
36
+ resolveDid: (args: { didUrl: string }) => Promise<{ didDocument?: Record<string, unknown> }>;
37
+ };
38
+
39
+ type PrivateKeyStore = {
40
+ getKey: (args: { alias: string }) => Promise<{
41
+ type: string;
42
+ alias: string;
43
+ privateKeyHex: string;
44
+ }>;
45
+ };
46
+
47
+ type AgentBundle = {
48
+ agent: VeramoAgent;
49
+ privateKeyStore: PrivateKeyStore;
50
+ };
51
+
52
+ let agentBundle: AgentBundle | undefined;
53
+
54
+ /** Per-pack cache so Veramo can resolve did:webvh without a global IdentityService. */
55
+ const webvhDidCache = new Map<string, Record<string, unknown>>();
56
+
57
+ function webvhResolverMethods(): Record<
58
+ string,
59
+ (did: string) => Promise<{
60
+ didDocument: Record<string, unknown> | null;
61
+ didDocumentMetadata: Record<string, unknown>;
62
+ didResolutionMetadata: Record<string, unknown>;
63
+ }>
64
+ > {
65
+ return {
66
+ webvh: async (did: string) => {
67
+ const cached = webvhDidCache.get(did);
68
+ if (cached) {
69
+ return {
70
+ didDocument: cached,
71
+ didDocumentMetadata: {},
72
+ didResolutionMetadata: { contentType: "application/did+ld+json" },
73
+ };
74
+ }
75
+ return {
76
+ didDocument: null,
77
+ didDocumentMetadata: {},
78
+ didResolutionMetadata: {
79
+ error: "notFound",
80
+ message: `did:webvh not available: ${did}`,
81
+ },
82
+ };
83
+ },
84
+ };
85
+ }
86
+
87
+ async function getAgentBundle(): Promise<AgentBundle> {
88
+ if (!agentBundle) {
89
+ agentBundle = await createAgentBundle();
90
+ }
91
+ return agentBundle;
92
+ }
93
+
94
+ async function createAgentBundle(): Promise<AgentBundle> {
95
+ const { createAgent } = require("@veramo/core");
96
+ const { DIDManager, MemoryDIDStore } = require("@veramo/did-manager");
97
+ const {
98
+ KeyManager,
99
+ MemoryKeyStore,
100
+ MemoryPrivateKeyStore,
101
+ } = require("@veramo/key-manager");
102
+ const { KeyManagementSystem } = require("@veramo/kms-local");
103
+ const { DIDComm } = require("@veramo/did-comm");
104
+ const { DIDResolverPlugin } = require("@veramo/did-resolver");
105
+ const { PeerDIDProvider, getResolver: getPeerResolver } = require("@veramo/did-provider-peer");
106
+ const { Resolver } = require("did-resolver");
107
+
108
+ const privateKeyStore = new MemoryPrivateKeyStore();
109
+ const agent = createAgent({
110
+ plugins: [
111
+ new KeyManager({
112
+ store: new MemoryKeyStore(),
113
+ kms: { local: new KeyManagementSystem(privateKeyStore) },
114
+ }),
115
+ new DIDManager({
116
+ store: new MemoryDIDStore(),
117
+ defaultProvider: "did:peer",
118
+ providers: {
119
+ "did:peer": new PeerDIDProvider({ defaultKms: "local" }),
120
+ },
121
+ }),
122
+ new DIDResolverPlugin({
123
+ resolver: new Resolver({ ...getPeerResolver(), ...webvhResolverMethods() }),
124
+ }),
125
+ new DIDComm(),
126
+ ],
127
+ }) as VeramoAgent;
128
+
129
+ return { agent, privateKeyStore };
130
+ }
131
+
132
+ export async function exportVeramoKeysForDid(
133
+ identity: { keys: Array<{ kid: string; publicKeyHex: string; meta?: Record<string, unknown> }> },
134
+ privateKeyStore: PrivateKeyStore
135
+ ): Promise<StoredVeramoKey[]> {
136
+ const keys: StoredVeramoKey[] = [];
137
+ for (const k of identity.keys) {
138
+ const pk = await privateKeyStore.getKey({ alias: k.kid });
139
+ keys.push({
140
+ type: pk.type,
141
+ kid: pk.alias,
142
+ privateKeyHex: pk.privateKeyHex,
143
+ publicKeyHex: k.publicKeyHex,
144
+ meta: k.meta,
145
+ kms: "local",
146
+ });
147
+ }
148
+ return keys;
149
+ }
150
+
151
+ /** Create a did:peer (num_algo 2) and export key material for persistence. */
152
+ export async function createPeerDidWithKeys(): Promise<{
153
+ did: string;
154
+ keys: StoredPeerDidBundle;
155
+ }> {
156
+ const { agent, privateKeyStore } = await getAgentBundle();
157
+ const identity = await agent.didManagerCreate({
158
+ provider: "did:peer",
159
+ options: { num_algo: 2 },
160
+ });
161
+ const veramoKeys = await exportVeramoKeysForDid(identity, privateKeyStore);
162
+ return {
163
+ did: identity.did,
164
+ keys: { veramoKeys },
165
+ };
166
+ }
167
+
168
+ /** @deprecated Prefer createPeerDidWithKeys — returns DID only. */
169
+ export async function createPeerDid(): Promise<string> {
170
+ const { did } = await createPeerDidWithKeys();
171
+ return did;
172
+ }
173
+
174
+ async function importPeerDidOnAgent(
175
+ did: string,
176
+ keys: StoredVeramoKey[]
177
+ ): Promise<void> {
178
+ const { agent } = await getAgentBundle();
179
+ try {
180
+ await agent.didManagerGet({ did });
181
+ return;
182
+ } catch {
183
+ // import below
184
+ }
185
+ await agent.didManagerImport({
186
+ did,
187
+ provider: "did:peer",
188
+ keys,
189
+ services: [],
190
+ });
191
+ }
192
+
193
+ async function ensureLocalPeerDid(
194
+ did: string,
195
+ store: IdentityStore,
196
+ picoId: string
197
+ ): Promise<void> {
198
+ const { agent } = await getAgentBundle();
199
+ try {
200
+ await agent.didManagerGet({ did });
201
+ return;
202
+ } catch {
203
+ // load from store
204
+ }
205
+ const subs = await store.listPeerSubscriptions(picoId);
206
+ const sub = subs.find((s) => s.peerDid === did);
207
+ const veramoKeys = peerKeysFromRecord(sub?.keys);
208
+ if (!veramoKeys) {
209
+ throw new IdentityError(`No local identity for DID ${did}`, 404);
210
+ }
211
+ await importPeerDidOnAgent(did, veramoKeys);
212
+ }
213
+
214
+ async function ensureWebvhDidOnAgent(
215
+ store: IdentityStore,
216
+ picoId: string
217
+ ): Promise<void> {
218
+ const did = await store.getWebvhDid(picoId);
219
+ if (!did) {
220
+ return;
221
+ }
222
+ const { agent } = await getAgentBundle();
223
+ try {
224
+ await agent.didManagerGet({ did });
225
+ return;
226
+ } catch {
227
+ // import below
228
+ }
229
+ const rawKeys = await store.getWebvhKeys(picoId);
230
+ const keyMaterial = storedKeysFromWebvhKeys(rawKeys || {});
231
+ if (!keyMaterial) {
232
+ return;
233
+ }
234
+ const log = await store.getWebvhLog(picoId);
235
+ if (!log?.length) {
236
+ return;
237
+ }
238
+ const resolved = await resolveLocalWebvhLog(log);
239
+ webvhDidCache.set(did, resolved.doc);
240
+ const veramoKeys = await webvhAgreementKeysForVeramo(
241
+ did,
242
+ resolved.doc,
243
+ keyMaterial
244
+ );
245
+ await agent.didManagerImport({
246
+ did,
247
+ provider: "did:webvh",
248
+ keys: veramoKeys,
249
+ services: Array.isArray(resolved.doc.service)
250
+ ? resolved.doc.service
251
+ : [],
252
+ });
253
+ }
254
+
255
+ /** Load all persisted peer DIDs for a pico onto the Veramo agent. */
256
+ export async function warmPeerDidsForPico(
257
+ store: IdentityStore,
258
+ picoId: string
259
+ ): Promise<void> {
260
+ for (const sub of await store.listPeerSubscriptions(picoId)) {
261
+ const veramoKeys = peerKeysFromRecord(sub.keys);
262
+ if (veramoKeys) {
263
+ await importPeerDidOnAgent(sub.peerDid, veramoKeys);
264
+ }
265
+ }
266
+ }
267
+
268
+ export async function resolvePeerDidDocument(
269
+ did: string
270
+ ): Promise<Record<string, unknown>> {
271
+ const { agent } = await getAgentBundle();
272
+ const resolved = await agent.resolveDid({ didUrl: did });
273
+ if (!resolved?.didDocument) {
274
+ throw new IdentityError(`DID not found: ${did}`, 404);
275
+ }
276
+ return resolved.didDocument;
277
+ }
278
+
279
+ export async function packDidCommMessage(
280
+ picoId: string,
281
+ message: DidCommPlainMessage,
282
+ from: string,
283
+ to: string,
284
+ store: IdentityStore,
285
+ options: {
286
+ resolveDid?: (did: string) => Promise<Record<string, unknown>>;
287
+ } = {}
288
+ ): Promise<string> {
289
+ const { agent } = await getAgentBundle();
290
+ if (from.startsWith("did:peer:")) {
291
+ await ensureLocalPeerDid(from, store, picoId);
292
+ }
293
+
294
+ let cachedWebvh = false;
295
+ if (to.startsWith("did:webvh:") && options.resolveDid) {
296
+ webvhDidCache.set(to, await options.resolveDid(to));
297
+ cachedWebvh = true;
298
+ }
299
+
300
+ try {
301
+ const packed = await agent.packDIDCommMessage({
302
+ message,
303
+ from,
304
+ to: [to],
305
+ packing: "authcrypt",
306
+ });
307
+ return packed.message;
308
+ } finally {
309
+ if (cachedWebvh) {
310
+ webvhDidCache.delete(to);
311
+ }
312
+ }
313
+ }
314
+
315
+ export async function unpackDidCommMessage(
316
+ picoId: string,
317
+ jwe: string,
318
+ store: IdentityStore
319
+ ): Promise<{ message: DidCommPlainMessage; metadata: Record<string, unknown> }> {
320
+ const { agent } = await getAgentBundle();
321
+ await ensureWebvhDidOnAgent(store, picoId);
322
+ const subs = await store.listPeerSubscriptions(picoId);
323
+ for (const sub of subs) {
324
+ const veramoKeys = peerKeysFromRecord(sub.keys);
325
+ if (veramoKeys) {
326
+ await importPeerDidOnAgent(sub.peerDid, veramoKeys);
327
+ }
328
+ }
329
+
330
+ let result: { message: DidCommPlainMessage; metaData?: Record<string, unknown> };
331
+ try {
332
+ result = await agent.unpackDIDCommMessage({ message: jwe });
333
+ } catch (err) {
334
+ throw new IdentityError(
335
+ `DIDComm unpack failed: ${(err as Error).message}`,
336
+ 401
337
+ );
338
+ }
339
+ const from = result.message.from;
340
+ if (from && from.startsWith("did:peer:")) {
341
+ try {
342
+ const resolved = await agent.resolveDid({ didUrl: from });
343
+ if (resolved?.didDocument) {
344
+ await store.putDidDoc(picoId, {
345
+ did: from,
346
+ doc: resolved.didDocument,
347
+ cachedAt: new Date().toISOString(),
348
+ });
349
+ }
350
+ } catch {
351
+ // best effort cache
352
+ }
353
+ }
354
+ return {
355
+ message: result.message,
356
+ metadata: (result.metaData || {}) as Record<string, unknown>,
357
+ };
358
+ }
359
+
360
+ export function resetVeramoAgentForTests(): void {
361
+ agentBundle = undefined;
362
+ webvhDidCache.clear();
363
+ }
@@ -0,0 +1,325 @@
1
+ import { ChannelConfig, Pico, PicoFramework } from "pico-framework";
2
+ import { IdentityStore } from "./store";
3
+ import type { WebvhLogEntry } from "./types";
4
+ import {
5
+ createWebvhCrypto,
6
+ generateWebvhKeyMaterial,
7
+ loadDidWebvhTs,
8
+ createPassthroughVerifier,
9
+ storedKeysFromWebvhKeys,
10
+ webvhKeysToStore,
11
+ type StoredWebvhKeyMaterial,
12
+ } from "./webvhCrypto";
13
+
14
+ export interface EnsureWebvhDidOptions {
15
+ isRoot?: boolean;
16
+ meshRootId?: string;
17
+ }
18
+
19
+ export function baseUrlToDidAddress(baseUrl: string): string {
20
+ const url = new URL(baseUrl);
21
+ if (url.port) {
22
+ return `${url.hostname}:${url.port}`;
23
+ }
24
+ return url.hostname;
25
+ }
26
+
27
+ /** Build an HTTP(S) did.jsonl URL from a portable did:webvh identifier. */
28
+ export function portableWebvhLogHttpUrl(did: string): string | null {
29
+ if (!did.startsWith("did:webvh:")) {
30
+ return null;
31
+ }
32
+ const parts = did.split(":");
33
+ if (parts.length < 4) {
34
+ return null;
35
+ }
36
+ const domainPart = parts[3];
37
+ const pathSegments = parts.slice(4).map((segment) => decodeURIComponent(segment));
38
+
39
+ let host: string;
40
+ let port: number | undefined;
41
+ if (/%3a/i.test(domainPart)) {
42
+ const [hostPart, portPart] = domainPart.split(/%3a/i);
43
+ if (!hostPart || !portPart) {
44
+ return null;
45
+ }
46
+ host = decodeURIComponent(hostPart);
47
+ port = parseInt(portPart, 10);
48
+ if (Number.isNaN(port)) {
49
+ return null;
50
+ }
51
+ } else {
52
+ host = decodeURIComponent(domainPart);
53
+ }
54
+
55
+ const hostPort = port ? `${host}:${port}` : host;
56
+ const useHttp =
57
+ host === "localhost" ||
58
+ host === "127.0.0.1" ||
59
+ host === "host.docker.internal" ||
60
+ host.endsWith(".localhost");
61
+ const protocol = useHttp ? "http" : "https";
62
+ const path =
63
+ pathSegments.length > 0
64
+ ? `/${pathSegments.join("/")}/did.jsonl`
65
+ : "/.well-known/did.jsonl";
66
+ return `${protocol}://${hostPort}${path}`;
67
+ }
68
+
69
+ async function fetchRemoteWebvhLog(
70
+ did: string,
71
+ fetchImpl: typeof fetch
72
+ ): Promise<WebvhLogEntry[] | null> {
73
+ const logUrl = portableWebvhLogHttpUrl(did);
74
+ if (!logUrl) {
75
+ return null;
76
+ }
77
+ try {
78
+ const res = await fetchImpl(logUrl);
79
+ if (!res.ok) {
80
+ return null;
81
+ }
82
+ const text = (await res.text()).trim();
83
+ if (!text) {
84
+ return null;
85
+ }
86
+ return text
87
+ .split("\n")
88
+ .map((line) => JSON.parse(line) as WebvhLogEntry);
89
+ } catch {
90
+ return null;
91
+ }
92
+ }
93
+
94
+ export function webvhPathsForPico(picoId: string): string[] {
95
+ return ["picos", picoId];
96
+ }
97
+
98
+ /** HTTP path prefix for a pico's did.jsonl (no leading slash). */
99
+ export function webvhHttpPath(picoId: string): string {
100
+ return `${webvhPathsForPico(picoId).join("/")}/did.jsonl`;
101
+ }
102
+
103
+ export function webvhDidJsonPath(picoId: string): string {
104
+ return `${webvhPathsForPico(picoId).join("/")}/did.json`;
105
+ }
106
+
107
+ export function meshRootIdFor(pf: PicoFramework, picoId: string): string {
108
+ let pico = pf.loadedPicos().find((p) => p.id === picoId);
109
+ if (!pico) {
110
+ return picoId;
111
+ }
112
+ while (pico.parent) {
113
+ pico = pf.getPico(pico.parent);
114
+ }
115
+ return pico.id;
116
+ }
117
+
118
+ function findPico(pf: PicoFramework, picoId: string): Pico | undefined {
119
+ return pf.loadedPicos().find((p) => p.id === picoId);
120
+ }
121
+
122
+ const INGRESS_CHANNEL: ChannelConfig = {
123
+ tags: ["didcomm", "ingress"],
124
+ eventPolicy: {
125
+ allow: [{ domain: "dido", name: "didcomm_message" }],
126
+ deny: [],
127
+ },
128
+ queryPolicy: {
129
+ allow: [],
130
+ deny: [{ rid: "*", name: "*" }],
131
+ },
132
+ };
133
+
134
+ async function ensureDidcommIngress(
135
+ pf: PicoFramework,
136
+ store: IdentityStore,
137
+ picoId: string,
138
+ baseUrl: string
139
+ ): Promise<string> {
140
+ const existing = await store.getDidcommIngressEci(picoId);
141
+ if (existing) {
142
+ return existing;
143
+ }
144
+ const pico = findPico(pf, picoId);
145
+ if (!pico) {
146
+ throw new Error(`Pico ${picoId} not loaded — cannot create DIDComm ingress`);
147
+ }
148
+ const chann = await pico.newChannel(INGRESS_CHANNEL);
149
+ const eci = chann.toReadOnly().id;
150
+ await store.putDidcommIngressEci(picoId, eci);
151
+ return eci;
152
+ }
153
+
154
+ function didcommServiceEndpoint(baseUrl: string, ingressEci: string): string {
155
+ const base = baseUrl.replace(/\/$/, "");
156
+ return `${base}/sky/event/${ingressEci}/none/dido/didcomm_message`;
157
+ }
158
+
159
+ export async function ensureWebvhDid(
160
+ store: IdentityStore,
161
+ pf: PicoFramework,
162
+ getBaseUrl: () => string,
163
+ picoId: string,
164
+ options: EnsureWebvhDidOptions = {}
165
+ ): Promise<string> {
166
+ const existing = await store.getWebvhDid(picoId);
167
+ if (existing) {
168
+ return existing;
169
+ }
170
+
171
+ const baseUrl = getBaseUrl();
172
+ if (!baseUrl) {
173
+ throw new Error("Engine base_url is required before provisioning did:webvh");
174
+ }
175
+
176
+ const webvh = await loadDidWebvhTs();
177
+ const keyMaterial = await generateWebvhKeyMaterial();
178
+ const crypto = await createWebvhCrypto(keyMaterial);
179
+ const ingressEci = await ensureDidcommIngress(pf, store, picoId, baseUrl);
180
+
181
+ const result = await webvh.createDID({
182
+ address: baseUrlToDidAddress(baseUrl),
183
+ paths: webvhPathsForPico(picoId),
184
+ portable: true,
185
+ alsoKnownAsWeb: true,
186
+ signer: crypto,
187
+ verifier: crypto,
188
+ updateKeys: [keyMaterial.updateKeyMultibase],
189
+ verificationMethods: [
190
+ keyMaterial.verificationMethod,
191
+ {
192
+ type: "Multikey",
193
+ publicKeyMultibase: keyMaterial.verificationMethod.publicKeyMultibase,
194
+ secretKeyMultibase: keyMaterial.verificationMethod.secretKeyMultibase,
195
+ purpose: "keyAgreement",
196
+ },
197
+ ],
198
+ services: [
199
+ {
200
+ id: "#didcomm",
201
+ type: "DIDCommMessaging",
202
+ serviceEndpoint: didcommServiceEndpoint(baseUrl, ingressEci),
203
+ accept: ["didcomm/v2"],
204
+ },
205
+ ],
206
+ });
207
+
208
+ const meshRootId =
209
+ options.meshRootId || meshRootIdFor(pf, picoId);
210
+ const publicIntro =
211
+ options.isRoot === true ||
212
+ (await store.getPublicIntro(picoId)) === true;
213
+
214
+ await store.putWebvhDid(picoId, result.did);
215
+ await store.putWebvhLog(picoId, result.log as unknown as WebvhLogEntry[]);
216
+ await store.putWebvhKeys(picoId, webvhKeysToStore(keyMaterial));
217
+ await store.putMeshRootId(picoId, meshRootId);
218
+ await store.putPublicIntro(picoId, publicIntro);
219
+ if (result.webDoc) {
220
+ await store.putWebvhWebDoc(picoId, result.webDoc as Record<string, unknown>);
221
+ }
222
+ await store.putDidDoc(picoId, {
223
+ did: result.did,
224
+ doc: result.doc as Record<string, unknown>,
225
+ cachedAt: new Date().toISOString(),
226
+ });
227
+
228
+ return result.did;
229
+ }
230
+
231
+ export async function ensureWebvhForLoadedPicos(
232
+ store: IdentityStore,
233
+ pf: PicoFramework,
234
+ getBaseUrl: () => string
235
+ ): Promise<void> {
236
+ const rootIds = new Set(pf.rootPicos().map((r) => r.id));
237
+ for (const pico of pf.loadedPicos()) {
238
+ await ensureWebvhDid(store, pf, getBaseUrl, pico.id, {
239
+ isRoot: rootIds.has(pico.id),
240
+ });
241
+ }
242
+ }
243
+
244
+ export function formatDidLogAsJsonl(log: WebvhLogEntry[]): string {
245
+ return log.map((entry) => JSON.stringify(entry)).join("\n") + "\n";
246
+ }
247
+
248
+ export async function resolveLocalWebvhLog(
249
+ log: WebvhLogEntry[]
250
+ ): Promise<{ did: string; doc: Record<string, unknown> }> {
251
+ const webvh = await loadDidWebvhTs();
252
+ const verifier = await createPassthroughVerifier();
253
+ const resolved = await webvh.resolveDIDFromLog(log as any, { verifier });
254
+ return {
255
+ did: resolved.did,
256
+ doc: resolved.doc as Record<string, unknown>,
257
+ };
258
+ }
259
+
260
+ export async function resolveWebvhDid(
261
+ store: IdentityStore,
262
+ did: string,
263
+ fetchImpl: typeof fetch = fetch
264
+ ): Promise<{ did: string; doc: Record<string, unknown> }> {
265
+ const webvh = await loadDidWebvhTs();
266
+ const localPicoId = await store.findPicoIdByWebvhDid(did);
267
+ if (localPicoId) {
268
+ const log = await store.getWebvhLog(localPicoId);
269
+ if (log && log.length > 0) {
270
+ return resolveLocalWebvhLog(log);
271
+ }
272
+ }
273
+ const remoteLog = await fetchRemoteWebvhLog(did, fetchImpl);
274
+ if (remoteLog && remoteLog.length > 0) {
275
+ return resolveLocalWebvhLog(remoteLog);
276
+ }
277
+
278
+ const result = await webvh.resolveDID(did, {
279
+ verifier: await createPassthroughVerifier(),
280
+ } as any);
281
+ if ("error" in result.meta && result.meta.error) {
282
+ throw new Error(`DID resolution failed: ${result.meta.error}`);
283
+ }
284
+ return {
285
+ did: result.did,
286
+ doc: result.doc as Record<string, unknown>,
287
+ };
288
+ }
289
+
290
+ export function picoIdFromWebvhHttpPath(pathname: string): string | null {
291
+ const match = pathname.match(/^\/picos\/([^/]+)\/did\.jsonl$/);
292
+ return match ? decodeURIComponent(match[1]) : null;
293
+ }
294
+
295
+ export function picoIdFromWebDidJsonPath(pathname: string): string | null {
296
+ const match = pathname.match(/^\/picos\/([^/]+)\/did\.json$/);
297
+ return match ? decodeURIComponent(match[1]) : null;
298
+ }
299
+
300
+ export async function parallelWebDocForPico(
301
+ store: IdentityStore,
302
+ picoId: string
303
+ ): Promise<Record<string, unknown> | null> {
304
+ const cached = await store.getWebvhWebDoc(picoId);
305
+ if (cached) {
306
+ return cached;
307
+ }
308
+ const did = await store.getWebvhDid(picoId);
309
+ const log = await store.getWebvhLog(picoId);
310
+ if (!did || !log || log.length === 0) {
311
+ return null;
312
+ }
313
+ const webvh = await loadDidWebvhTs();
314
+ const { doc } = await resolveLocalWebvhLog(log);
315
+ return webvh.generateParallelDidWeb(did, doc as any) as Record<string, unknown>;
316
+ }
317
+
318
+ export function keysFromStore(
319
+ raw: Record<string, unknown> | null
320
+ ): StoredWebvhKeyMaterial | null {
321
+ if (!raw) {
322
+ return null;
323
+ }
324
+ return storedKeysFromWebvhKeys(raw);
325
+ }