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,371 @@
1
+ import * as cuid from "cuid";
2
+ import fetch from "cross-fetch";
3
+ import { PicoFramework } from "pico-framework";
4
+ import { IdentityStore } from "./store";
5
+ import type { PeerSubscriptionRecord } from "./types";
6
+ import type { DidCommPlainMessage, IdentityService } from "./IdentityService";
7
+ import {
8
+ SKY_EVENT,
9
+ SKY_QUERY,
10
+ SKY_QUERY_RESPONSE,
11
+ parseSkyEventBody,
12
+ parseSkyQueryBody,
13
+ } from "./skyProtocol";
14
+ import { packDidCommMessage } from "./veramoDidComm";
15
+ import { IdentityError } from "./errors";
16
+
17
+ export interface CrossPicoEventInput {
18
+ domain: string;
19
+ name: string;
20
+ attrs?: Record<string, unknown>;
21
+ eid?: string;
22
+ }
23
+
24
+ export interface CrossPicoQueryInput {
25
+ rid: string;
26
+ name: string;
27
+ args?: Record<string, unknown>;
28
+ }
29
+
30
+ export interface CrossPicoDeps {
31
+ store: IdentityStore;
32
+ pf: PicoFramework;
33
+ getBaseUrl: () => string;
34
+ identity: IdentityService;
35
+ }
36
+
37
+ function remotePeerDid(sub: PeerSubscriptionRecord): string {
38
+ const did = sub.remotePeerDid || sub.remoteDid;
39
+ if (!did) {
40
+ throw new IdentityError("Subscription missing remote peer DID", 400);
41
+ }
42
+ return did;
43
+ }
44
+
45
+ function remoteTxHost(sub: PeerSubscriptionRecord, fallback: string): string {
46
+ const host = sub.remoteTxHost || fallback;
47
+ return host.replace(/\/$/, "");
48
+ }
49
+
50
+ export async function usesLocalDispatch(
51
+ store: IdentityStore,
52
+ pf: PicoFramework,
53
+ fromPicoId: string,
54
+ toPicoId: string,
55
+ sub: PeerSubscriptionRecord
56
+ ): Promise<boolean> {
57
+ const fromMesh = await store.getMeshRootId(fromPicoId);
58
+ const toMesh = await store.getMeshRootId(toPicoId);
59
+ if (!fromMesh || !toMesh || fromMesh !== toMesh) {
60
+ return false;
61
+ }
62
+ if (sub.remoteMeshRootId && sub.remoteMeshRootId !== fromMesh) {
63
+ return false;
64
+ }
65
+ return pf.loadedPicos().some((p) => p.id === toPicoId);
66
+ }
67
+
68
+ export async function resolveRecipientPicoId(
69
+ store: IdentityStore,
70
+ pf: PicoFramework,
71
+ fromPicoId: string,
72
+ subscriptionId: string
73
+ ): Promise<string | undefined> {
74
+ const sub = await store.getPeerSubscription(fromPicoId, subscriptionId);
75
+ if (!sub) {
76
+ return undefined;
77
+ }
78
+ const remotePeer = sub.remotePeerDid || sub.remoteDid;
79
+ if (remotePeer) {
80
+ const byPeer = await store.findPicoIdByLocalPeerDid(remotePeer);
81
+ if (byPeer && pf.loadedPicos().some((p) => p.id === byPeer)) {
82
+ return byPeer;
83
+ }
84
+ }
85
+ if (sub.remoteWebvhDid) {
86
+ const byWebvh = await store.findPicoIdByWebvhDid(sub.remoteWebvhDid);
87
+ if (byWebvh && pf.loadedPicos().some((p) => p.id === byWebvh)) {
88
+ return byWebvh;
89
+ }
90
+ }
91
+ return undefined;
92
+ }
93
+
94
+ export async function crossPicoEvent(
95
+ deps: CrossPicoDeps,
96
+ fromPicoId: string,
97
+ toPicoId: string | undefined,
98
+ subscriptionId: string,
99
+ event: CrossPicoEventInput
100
+ ): Promise<{ eid: string; responses: unknown[] }> {
101
+ const sub = await deps.store.getPeerSubscription(fromPicoId, subscriptionId);
102
+ if (!sub || !sub.rxEci) {
103
+ throw new IdentityError(`Unknown subscription ${subscriptionId}`, 404);
104
+ }
105
+
106
+ const callerDid = await deps.store.getWebvhDid(fromPicoId);
107
+ const attrs = { ...(event.attrs || {}), callerDid: callerDid || undefined };
108
+
109
+ const to =
110
+ toPicoId ||
111
+ (await resolveRecipientPicoId(deps.store, deps.pf, fromPicoId, subscriptionId));
112
+
113
+ if (
114
+ to &&
115
+ (await usesLocalDispatch(deps.store, deps.pf, fromPicoId, to, sub))
116
+ ) {
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
+ );
128
+ }
129
+
130
+ return sendSkyEvent(deps, fromPicoId, sub, event, attrs);
131
+ }
132
+
133
+ export async function crossPicoQuery(
134
+ deps: CrossPicoDeps,
135
+ fromPicoId: string,
136
+ toPicoId: string | undefined,
137
+ subscriptionId: string,
138
+ query: CrossPicoQueryInput
139
+ ): Promise<unknown> {
140
+ const sub = await deps.store.getPeerSubscription(fromPicoId, subscriptionId);
141
+ if (!sub || !sub.rxEci) {
142
+ throw new IdentityError(`Unknown subscription ${subscriptionId}`, 404);
143
+ }
144
+
145
+ const to =
146
+ toPicoId ||
147
+ (await resolveRecipientPicoId(deps.store, deps.pf, fromPicoId, subscriptionId));
148
+
149
+ if (
150
+ to &&
151
+ (await usesLocalDispatch(deps.store, deps.pf, fromPicoId, to, sub))
152
+ ) {
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
+ );
163
+ }
164
+
165
+ return sendSkyQuery(deps, fromPicoId, sub, query);
166
+ }
167
+
168
+ async function findRecipientSub(
169
+ store: IdentityStore,
170
+ toPicoId: string,
171
+ 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
+ );
179
+ }
180
+ return recipientSub;
181
+ }
182
+
183
+ async function sendSkyEvent(
184
+ deps: CrossPicoDeps,
185
+ fromPicoId: string,
186
+ sub: PeerSubscriptionRecord,
187
+ event: CrossPicoEventInput,
188
+ attrs: Record<string, unknown>
189
+ ): Promise<{ eid: string; responses: unknown[] }> {
190
+ const message = deps.identity.generateMessage({
191
+ type: SKY_EVENT,
192
+ from: sub.peerDid,
193
+ to: [remotePeerDid(sub)],
194
+ body: {
195
+ sky_version: "1.0",
196
+ eid: event.eid || "none",
197
+ domain: event.domain,
198
+ name: event.name,
199
+ attrs,
200
+ },
201
+ });
202
+ const jwe = await packDidCommMessage(
203
+ fromPicoId,
204
+ message,
205
+ sub.peerDid,
206
+ remotePeerDid(sub),
207
+ deps.store,
208
+ { resolveDid: (did) => deps.identity.resolveDid("", did) }
209
+ );
210
+ const endpoint = await resolveRemoteDidcommEndpoint(deps, sub);
211
+ const res = await fetch(endpoint, {
212
+ method: "POST",
213
+ headers: {
214
+ "Content-Type": "application/didcomm-encrypted+json",
215
+ },
216
+ body: jwe,
217
+ });
218
+ if (!res.ok) {
219
+ throw new IdentityError(
220
+ `DIDComm event delivery failed: HTTP ${res.status}`,
221
+ res.status
222
+ );
223
+ }
224
+ const data = await res.json();
225
+ return {
226
+ eid: data.eid || "none",
227
+ responses: data.responses || data.directives || [],
228
+ };
229
+ }
230
+
231
+ async function sendSkyQuery(
232
+ deps: CrossPicoDeps,
233
+ fromPicoId: string,
234
+ sub: PeerSubscriptionRecord,
235
+ query: CrossPicoQueryInput
236
+ ): Promise<unknown> {
237
+ const queryId = cuid();
238
+ const message = deps.identity.generateMessage({
239
+ type: SKY_QUERY,
240
+ from: sub.peerDid,
241
+ to: [remotePeerDid(sub)],
242
+ body: {
243
+ sky_version: "1.0",
244
+ rid: query.rid,
245
+ name: query.name,
246
+ args: query.args || {},
247
+ },
248
+ });
249
+ message.id = queryId;
250
+ const jwe = await packDidCommMessage(
251
+ fromPicoId,
252
+ message,
253
+ sub.peerDid,
254
+ remotePeerDid(sub),
255
+ deps.store,
256
+ { resolveDid: (did) => deps.identity.resolveDid("", did) }
257
+ );
258
+ const endpoint = await resolveRemoteDidcommEndpoint(deps, sub);
259
+ const res = await fetch(endpoint, {
260
+ method: "POST",
261
+ headers: {
262
+ "Content-Type": "application/didcomm-encrypted+json",
263
+ },
264
+ body: jwe,
265
+ });
266
+ if (!res.ok) {
267
+ const detail = await res.text();
268
+ throw new IdentityError(
269
+ `DIDComm query delivery failed: HTTP ${res.status} ${detail}`,
270
+ res.status
271
+ );
272
+ }
273
+ const data = await res.json();
274
+ if (data.result !== undefined) {
275
+ return data.result;
276
+ }
277
+ if (data.status === "error") {
278
+ throw new IdentityError(data.error?.message || "Remote query failed", 502);
279
+ }
280
+ return data;
281
+ }
282
+
283
+ async function resolveRemoteDidcommEndpoint(
284
+ deps: CrossPicoDeps,
285
+ sub: PeerSubscriptionRecord
286
+ ): Promise<string> {
287
+ if (sub.remoteDidcommEndpoint) {
288
+ return sub.remoteDidcommEndpoint;
289
+ }
290
+ if (sub.remoteWebvhDid) {
291
+ try {
292
+ const doc = await deps.identity.resolveDid("", sub.remoteWebvhDid);
293
+ return extractDidcommEndpoint(doc);
294
+ } catch {
295
+ // fall through
296
+ }
297
+ }
298
+ const remoteDid = remotePeerDid(sub);
299
+ const doc = await deps.identity.resolveDid("", remoteDid);
300
+ return extractDidcommEndpoint(doc);
301
+ }
302
+
303
+ export function extractDidcommEndpoint(doc: Record<string, unknown>): string {
304
+ const services = doc.service as Array<Record<string, unknown>> | undefined;
305
+ if (!services || services.length === 0) {
306
+ throw new IdentityError("DID document has no service endpoints", 404);
307
+ }
308
+ const svc = services.find(
309
+ (s) =>
310
+ s.type === "DIDCommMessaging" ||
311
+ s.type === "Messaging" ||
312
+ s.type === "did-communication"
313
+ );
314
+ const endpoint = svc?.serviceEndpoint;
315
+ if (typeof endpoint === "string") {
316
+ return endpoint;
317
+ }
318
+ if (
319
+ endpoint &&
320
+ typeof endpoint === "object" &&
321
+ typeof (endpoint as { uri?: string }).uri === "string"
322
+ ) {
323
+ return (endpoint as { uri: string }).uri;
324
+ }
325
+ const fallback = services[0].serviceEndpoint;
326
+ if (typeof fallback === "string") {
327
+ return fallback;
328
+ }
329
+ throw new IdentityError("Could not extract DIDComm service endpoint", 404);
330
+ }
331
+
332
+ export function buildQueryResponseMessage(
333
+ identity: IdentityService,
334
+ fromPeerDid: string,
335
+ toPeerDid: string,
336
+ thid: string,
337
+ result: unknown
338
+ ): DidCommPlainMessage {
339
+ return identity.generateMessage({
340
+ type: SKY_QUERY_RESPONSE,
341
+ from: fromPeerDid,
342
+ to: [toPeerDid],
343
+ thid,
344
+ body: {
345
+ sky_version: "1.0",
346
+ status: "ok",
347
+ result,
348
+ },
349
+ });
350
+ }
351
+
352
+ export function buildQueryErrorResponseMessage(
353
+ identity: IdentityService,
354
+ fromPeerDid: string,
355
+ toPeerDid: string,
356
+ thid: string,
357
+ message: string,
358
+ code = "query_failed"
359
+ ): DidCommPlainMessage {
360
+ return identity.generateMessage({
361
+ type: SKY_QUERY_RESPONSE,
362
+ from: fromPeerDid,
363
+ to: [toPeerDid],
364
+ thid,
365
+ body: {
366
+ sky_version: "1.0",
367
+ status: "error",
368
+ error: { code, message },
369
+ },
370
+ });
371
+ }
@@ -0,0 +1,51 @@
1
+ import { PicoDb, PicoDbKey } from "pico-framework";
2
+
3
+ export async function dbGet<T>(db: PicoDb, key: PicoDbKey): Promise<T | null> {
4
+ try {
5
+ const value = await db.get(key);
6
+ return value === undefined ? null : (value as T);
7
+ } catch (err: any) {
8
+ if (err && (err.notFound || err.code === "LEVEL_NOT_FOUND")) {
9
+ return null;
10
+ }
11
+ throw err;
12
+ }
13
+ }
14
+
15
+ export async function dbPut(
16
+ db: PicoDb,
17
+ key: PicoDbKey,
18
+ value: unknown
19
+ ): Promise<void> {
20
+ if (value === undefined || value === null) {
21
+ await db.del(key);
22
+ return;
23
+ }
24
+ await db.put(key, value);
25
+ }
26
+
27
+ export async function dbDel(db: PicoDb, key: PicoDbKey): Promise<void> {
28
+ try {
29
+ await db.del(key);
30
+ } catch (err: any) {
31
+ if (err && (err.notFound || err.code === "LEVEL_NOT_FOUND")) {
32
+ return;
33
+ }
34
+ throw err;
35
+ }
36
+ }
37
+
38
+ export async function dbList<T = unknown>(
39
+ db: PicoDb,
40
+ prefix: PicoDbKey
41
+ ): Promise<{ key: PicoDbKey; value: T }[]> {
42
+ const out: { key: PicoDbKey; value: T }[] = [];
43
+ const iter = db.iterator({
44
+ gte: prefix,
45
+ lte: prefix.concat([undefined] as any),
46
+ });
47
+ for await (const [key, value] of iter) {
48
+ out.push({ key, value: value as T });
49
+ }
50
+ return out;
51
+ }
@@ -0,0 +1,54 @@
1
+ import { Express, Request, Response } from "express";
2
+ import { IdentityService } from "./IdentityService";
3
+ import { IdentityError } from "./errors";
4
+
5
+ export function registerDidcommIngressRoutes(
6
+ app: Express,
7
+ identity: IdentityService
8
+ ): void {
9
+ app.post(
10
+ "/sky/event/:eci/none/dido/didcomm_message",
11
+ async (req: Request, res: Response) => {
12
+ try {
13
+ const jwe = extractJweBody(req);
14
+ const result = await identity.handleDidcommIngress(
15
+ req.params.eci,
16
+ jwe
17
+ );
18
+ res.status(200).json(result);
19
+ } catch (err) {
20
+ sendIngressError(res, err);
21
+ }
22
+ }
23
+ );
24
+ }
25
+
26
+ function extractJweBody(req: Request): string {
27
+ const body = req.body;
28
+ if (typeof body === "string") {
29
+ return body;
30
+ }
31
+ if (body && typeof body === "object") {
32
+ const obj = body as Record<string, unknown>;
33
+ if (typeof obj.protected === "string" || typeof obj.ciphertext === "string") {
34
+ return JSON.stringify(body);
35
+ }
36
+ for (const key of ["jwe", "message", "payload"]) {
37
+ if (typeof obj[key] === "string") {
38
+ return obj[key] as string;
39
+ }
40
+ }
41
+ if (typeof obj.body === "string") {
42
+ return obj.body;
43
+ }
44
+ }
45
+ throw new IdentityError("Request body must be a DIDComm JWE", 400);
46
+ }
47
+
48
+ function sendIngressError(res: Response, err: unknown): void {
49
+ if (err instanceof IdentityError) {
50
+ res.status(err.statusCode).json({ error: err.message });
51
+ return;
52
+ }
53
+ res.status(500).json({ error: (err as Error).message || "Internal error" });
54
+ }