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,121 @@
1
+ "use strict";
2
+ /**
3
+ * DIDComm SKY rotation notices for portable did:webvh move (Phase D).
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.notifyPeersOfWebvhRotation = notifyPeersOfWebvhRotation;
7
+ exports.handleSkyRotateAtIngress = handleSkyRotateAtIngress;
8
+ const cross_fetch_1 = require("cross-fetch");
9
+ const errors_1 = require("./errors");
10
+ const establishSubscription_1 = require("./establishSubscription");
11
+ const crossPico_1 = require("./crossPico");
12
+ const skyProtocol_1 = require("./skyProtocol");
13
+ const veramoDidComm_1 = require("./veramoDidComm");
14
+ function findPico(pf, picoId) {
15
+ return pf.loadedPicos().find((p) => p.id === picoId);
16
+ }
17
+ async function resolveDidcommEndpointForDid(identity, did, remoteDidcommEndpoint) {
18
+ if (remoteDidcommEndpoint) {
19
+ return remoteDidcommEndpoint;
20
+ }
21
+ const doc = await identity.resolveDid("", did);
22
+ return (0, crossPico_1.extractDidcommEndpoint)(doc);
23
+ }
24
+ async function postJwe(endpoint, jwe) {
25
+ const res = await (0, cross_fetch_1.default)(endpoint, {
26
+ method: "POST",
27
+ headers: { "Content-Type": "application/didcomm-encrypted+json" },
28
+ body: jwe,
29
+ });
30
+ if (!res.ok) {
31
+ const detail = await res.text();
32
+ throw new errors_1.IdentityError(`DIDComm POST failed: HTTP ${res.status} ${detail}`, res.status);
33
+ }
34
+ }
35
+ async function deliverRotateNotice(deps, fromPicoId, toPeerDid, remoteWebvhDid, remoteDidcommEndpoint, body, fromPrior) {
36
+ const fromWebvh = await deps.store.getWebvhDid(fromPicoId);
37
+ const sub = (await deps.store.listPeerSubscriptions(fromPicoId)).find((s) => s.remotePeerDid === toPeerDid || s.remoteDid === toPeerDid);
38
+ const fromPeer = sub === null || sub === void 0 ? void 0 : sub.peerDid;
39
+ if (!fromPeer) {
40
+ throw new errors_1.IdentityError(`No local peer DID for subscription to ${toPeerDid}`, 404);
41
+ }
42
+ const message = Object.assign({ id: `rotate-${Date.now()}`, typ: "application/didcomm-plain+json", type: skyProtocol_1.SKY_ROTATE, from: fromPeer, to: [toPeerDid], body, created_time: Math.floor(Date.now() / 1000) }, (fromPrior ? { from_prior: fromPrior } : {}));
43
+ const packed = await (0, veramoDidComm_1.packDidCommMessage)(fromPicoId, message, fromPeer, toPeerDid, deps.store, { resolveDid: (did) => deps.identity.resolveDid("", did) });
44
+ const endpoint = await resolveDidcommEndpointForDid(deps.identity, remoteWebvhDid || toPeerDid, remoteDidcommEndpoint);
45
+ await postJwe(endpoint, packed);
46
+ }
47
+ /** Notify established peers that this pico's did:webvh location changed. */
48
+ async function notifyPeersOfWebvhRotation(deps, picoId, relocation) {
49
+ const baseUrl = deps.getBaseUrl().replace(/\/$/, "");
50
+ const body = {
51
+ sky_version: "1.0",
52
+ prior_webvh_did: relocation.priorDid,
53
+ new_webvh_did: relocation.newDid,
54
+ new_tx_host: baseUrl,
55
+ new_didcomm_endpoint: relocation.didcommEndpoint,
56
+ };
57
+ const subs = await deps.store.listPeerSubscriptions(picoId);
58
+ let sent = 0;
59
+ for (const sub of subs) {
60
+ const remotePeer = sub.remotePeerDid || sub.remoteDid;
61
+ if (!remotePeer) {
62
+ continue;
63
+ }
64
+ try {
65
+ await deliverRotateNotice(deps, picoId, remotePeer, sub.remoteWebvhDid, sub.remoteDidcommEndpoint, body, relocation.priorDid !== relocation.newDid ? relocation.priorDid : undefined);
66
+ sent += 1;
67
+ }
68
+ catch (err) {
69
+ const msg = err instanceof Error ? err.message : String(err);
70
+ console.warn(`[portable-move] SKY rotate to ${remotePeer} failed (import continues): ${msg}`);
71
+ }
72
+ }
73
+ return sent;
74
+ }
75
+ /** Apply a SKY rotate message on the recipient pico. */
76
+ async function handleSkyRotateAtIngress(deps, recipientPicoId, message) {
77
+ const senderDid = message.from;
78
+ if (!senderDid) {
79
+ throw new errors_1.IdentityError("SKY rotate missing from", 400);
80
+ }
81
+ const rotate = (0, skyProtocol_1.parseSkyRotateBody)(message.body);
82
+ const sub = await deps.store.findPeerSubscriptionBySenderDid(recipientPicoId, senderDid);
83
+ if (!sub) {
84
+ throw new errors_1.IdentityError("unknown_subscription", 404);
85
+ }
86
+ await (0, establishSubscription_1.linkRemotePeer)(deps.store, recipientPicoId, sub.subscriptionId, {
87
+ remotePeerDid: senderDid,
88
+ remoteWebvhDid: rotate.new_webvh_did,
89
+ remoteTxHost: rotate.new_tx_host,
90
+ remoteDidcommEndpoint: rotate.new_didcomm_endpoint,
91
+ });
92
+ const pending = (await deps.store.getPendingRotations(recipientPicoId)) || [];
93
+ pending.push({
94
+ priorDid: rotate.prior_webvh_did,
95
+ newDid: rotate.new_webvh_did,
96
+ peerDid: senderDid,
97
+ subscriptionId: sub.subscriptionId,
98
+ receivedAt: new Date().toISOString(),
99
+ });
100
+ await deps.store.putPendingRotations(recipientPicoId, pending);
101
+ const pico = findPico(deps.pf, recipientPicoId);
102
+ if (pico) {
103
+ await pico.event({
104
+ eci: pico.id,
105
+ domain: "wrangler",
106
+ name: "webvh_peer_rotated",
107
+ data: {
108
+ attrs: (0, skyProtocol_1.skyRotateToWranglerAttrs)(rotate, {
109
+ Id: sub.subscriptionId,
110
+ peer_did: senderDid,
111
+ }),
112
+ },
113
+ time: Date.now(),
114
+ });
115
+ }
116
+ return {
117
+ status: "ok",
118
+ subscriptionId: sub.subscriptionId,
119
+ new_webvh_did: rotate.new_webvh_did,
120
+ };
121
+ }
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.IdentityStore = exports.IDENTITY_PREFIX = void 0;
4
4
  exports.migrateFromDidO = migrateFromDidO;
5
5
  const dbHelpers_1 = require("./dbHelpers");
6
+ const peerDid4_1 = require("./peerDid4");
6
7
  exports.IDENTITY_PREFIX = "pico-identity";
7
8
  const FIELD = {
8
9
  webvhDid: "webvhDid",
@@ -212,11 +213,14 @@ exports.IdentityStore = IdentityStore;
212
213
  async function migrateFromDidO(_picoId) {
213
214
  return;
214
215
  }
215
- /** Match did:peer short/long forms (numalgo 0/2). */
216
+ /** Match did:peer short/long forms (numalgo 0/2/4). */
216
217
  function peerDidMatches(stored, incoming) {
217
218
  if (stored === incoming) {
218
219
  return true;
219
220
  }
221
+ if (stored.startsWith("did:peer:4") || incoming.startsWith("did:peer:4")) {
222
+ return (0, peerDid4_1.peerDid4Matches)(stored, incoming);
223
+ }
220
224
  const storedShort = peerDidShortForm(stored);
221
225
  const incomingShort = peerDidShortForm(incoming);
222
226
  return storedShort.length > 0 && storedShort === incomingShort;
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+ /**
3
+ * Keep wrangler subscription ent buses aligned with engine identity store after import.
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.syncLayer2EstablishedFromIdentity = syncLayer2EstablishedFromIdentity;
7
+ const SUBSCRIPTION_RID = "io.picolabs.subscription";
8
+ function busId(bus) {
9
+ const id = bus["Id"];
10
+ return typeof id === "string" ? id : undefined;
11
+ }
12
+ function mergeIdentityIntoBus(bus, rec) {
13
+ const out = Object.assign(Object.assign({}, bus), { layer2: true });
14
+ if (rec.rxEci) {
15
+ out["Rx"] = rec.rxEci;
16
+ }
17
+ if (rec.peerDid) {
18
+ out["Rx_did"] = rec.peerDid;
19
+ }
20
+ if (rec.remotePeerDid || rec.remoteDid) {
21
+ out["Tx_did"] =
22
+ out["Tx_did"] || rec.remoteWebvhDid || rec.remotePeerDid || rec.remoteDid;
23
+ }
24
+ if (rec.remoteWebvhDid) {
25
+ out["Tx_did"] = rec.remoteWebvhDid;
26
+ }
27
+ if (rec.remoteTxHost) {
28
+ out["Tx_host"] = rec.remoteTxHost;
29
+ }
30
+ return out;
31
+ }
32
+ function findBusInPools(id, pools) {
33
+ return pools.find((b) => busId(b) === id);
34
+ }
35
+ /** Merge identity peer subscriptions into ent:established (Layer 2 DID relationships). */
36
+ async function syncLayer2EstablishedFromIdentity(store, pf, picoId) {
37
+ const pico = pf.getPico(picoId);
38
+ if (!(pico === null || pico === void 0 ? void 0 : pico.rulesets[SUBSCRIPTION_RID])) {
39
+ return;
40
+ }
41
+ const peerSubs = await store.listPeerSubscriptions(picoId);
42
+ if (peerSubs.length === 0) {
43
+ return;
44
+ }
45
+ const establishedRaw = await pico.getEnt(SUBSCRIPTION_RID, "established");
46
+ let list = Array.isArray(establishedRaw)
47
+ ? establishedRaw.map((b) => b && typeof b === "object" ? Object.assign({}, b) : {})
48
+ : [];
49
+ const inbound = await pico.getEnt(SUBSCRIPTION_RID, "inbound");
50
+ const outbound = await pico.getEnt(SUBSCRIPTION_RID, "outbound");
51
+ const pools = [
52
+ ...(Array.isArray(inbound)
53
+ ? inbound.filter((b) => b && typeof b === "object")
54
+ : []),
55
+ ...(Array.isArray(outbound)
56
+ ? outbound.filter((b) => b && typeof b === "object")
57
+ : []),
58
+ ];
59
+ for (const rec of peerSubs) {
60
+ const id = rec.subscriptionId;
61
+ let idx = list.findIndex((b) => busId(b) === id);
62
+ if (idx >= 0) {
63
+ list[idx] = mergeIdentityIntoBus(list[idx], rec);
64
+ continue;
65
+ }
66
+ const fromPool = findBusInPools(id, pools);
67
+ if (fromPool || rec.remotePeerDid || rec.remoteWebvhDid) {
68
+ list.push(mergeIdentityIntoBus(fromPool || { Id: id }, rec));
69
+ }
70
+ }
71
+ await pico.putEnt(SUBSCRIPTION_RID, "established", list);
72
+ }
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.exportVeramoKeysForDid = exportVeramoKeysForDid;
4
+ exports.createPeerDid2WithKeys = createPeerDid2WithKeys;
4
5
  exports.createPeerDidWithKeys = createPeerDidWithKeys;
5
6
  exports.createPeerDid = createPeerDid;
6
7
  exports.warmPeerDidsForPico = warmPeerDidsForPico;
@@ -10,6 +11,8 @@ exports.unpackDidCommMessage = unpackDidCommMessage;
10
11
  exports.resetVeramoAgentForTests = resetVeramoAgentForTests;
11
12
  const errors_1 = require("./errors");
12
13
  const peerDid_1 = require("./peerDid");
14
+ const peerDid4_1 = require("./peerDid4");
15
+ const peerDid4Create_1 = require("./peerDid4Create");
13
16
  const webvhCrypto_1 = require("./webvhCrypto");
14
17
  const webvh_1 = require("./webvh");
15
18
  let agentBundle;
@@ -52,6 +55,32 @@ async function createAgentBundle() {
52
55
  const { DIDResolverPlugin } = require("@veramo/did-resolver");
53
56
  const { PeerDIDProvider, getResolver: getPeerResolver } = require("@veramo/did-provider-peer");
54
57
  const { Resolver } = require("did-resolver");
58
+ const basePeerResolver = getPeerResolver();
59
+ const peerResolver = Object.assign(Object.assign({}, basePeerResolver), { peer: async (did, parsed, resolver, options) => {
60
+ if ((0, peerDid4_1.isPeerDid4)(did)) {
61
+ try {
62
+ const didDocument = (0, peerDid4_1.resolvePeerDid4)(did);
63
+ return {
64
+ didDocument,
65
+ didDocumentMetadata: {},
66
+ didResolutionMetadata: {
67
+ contentType: "application/did+ld+json",
68
+ },
69
+ };
70
+ }
71
+ catch (err) {
72
+ return {
73
+ didDocument: null,
74
+ didDocumentMetadata: {},
75
+ didResolutionMetadata: {
76
+ error: "invalidDid",
77
+ message: err.message,
78
+ },
79
+ };
80
+ }
81
+ }
82
+ return basePeerResolver.peer(did, parsed, resolver, options);
83
+ } });
55
84
  const privateKeyStore = new MemoryPrivateKeyStore();
56
85
  const agent = createAgent({
57
86
  plugins: [
@@ -67,7 +96,7 @@ async function createAgentBundle() {
67
96
  },
68
97
  }),
69
98
  new DIDResolverPlugin({
70
- resolver: new Resolver(Object.assign(Object.assign({}, getPeerResolver()), webvhResolverMethods())),
99
+ resolver: new Resolver(Object.assign(Object.assign({}, peerResolver), webvhResolverMethods())),
71
100
  }),
72
101
  new DIDComm(),
73
102
  ],
@@ -90,7 +119,7 @@ async function exportVeramoKeysForDid(identity, privateKeyStore) {
90
119
  return keys;
91
120
  }
92
121
  /** Create a did:peer (num_algo 2) and export key material for persistence. */
93
- async function createPeerDidWithKeys() {
122
+ async function createPeerDid2WithKeys() {
94
123
  const { agent, privateKeyStore } = await getAgentBundle();
95
124
  const identity = await agent.didManagerCreate({
96
125
  provider: "did:peer",
@@ -102,6 +131,16 @@ async function createPeerDidWithKeys() {
102
131
  keys: { veramoKeys },
103
132
  };
104
133
  }
134
+ /** Create a did:peer:4 (long form) and export key material for persistence. */
135
+ async function createPeerDidWithKeys() {
136
+ const created = (0, peerDid4Create_1.createPeerDid4WithKeys)();
137
+ await getAgentBundle();
138
+ await importPeerDidOnAgent(created.did, created.keys.veramoKeys);
139
+ return {
140
+ did: created.did,
141
+ keys: created.keys,
142
+ };
143
+ }
105
144
  /** @deprecated Prefer createPeerDidWithKeys — returns DID only. */
106
145
  async function createPeerDid() {
107
146
  const { did } = await createPeerDidWithKeys();
@@ -6,6 +6,8 @@ exports.webvhPathsForPico = webvhPathsForPico;
6
6
  exports.webvhHttpPath = webvhHttpPath;
7
7
  exports.webvhDidJsonPath = webvhDidJsonPath;
8
8
  exports.meshRootIdFor = meshRootIdFor;
9
+ exports.ensureDidcommIngress = ensureDidcommIngress;
10
+ exports.didcommServiceEndpoint = didcommServiceEndpoint;
9
11
  exports.ensureWebvhDid = ensureWebvhDid;
10
12
  exports.ensureWebvhForLoadedPicos = ensureWebvhForLoadedPicos;
11
13
  exports.formatDidLogAsJsonl = formatDidLogAsJsonl;
@@ -117,7 +119,7 @@ const INGRESS_CHANNEL = {
117
119
  deny: [{ rid: "*", name: "*" }],
118
120
  },
119
121
  };
120
- async function ensureDidcommIngress(pf, store, picoId, baseUrl) {
122
+ async function ensureDidcommIngress(store, pf, picoId, baseUrl) {
121
123
  const existing = await store.getDidcommIngressEci(picoId);
122
124
  if (existing) {
123
125
  return existing;
@@ -147,7 +149,7 @@ async function ensureWebvhDid(store, pf, getBaseUrl, picoId, options = {}) {
147
149
  const webvh = await (0, webvhCrypto_1.loadDidWebvhTs)();
148
150
  const keyMaterial = await (0, webvhCrypto_1.generateWebvhKeyMaterial)();
149
151
  const crypto = await (0, webvhCrypto_1.createWebvhCrypto)(keyMaterial);
150
- const ingressEci = await ensureDidcommIngress(pf, store, picoId, baseUrl);
152
+ const ingressEci = await ensureDidcommIngress(store, pf, picoId, baseUrl);
151
153
  const result = await webvh.createDID({
152
154
  address: baseUrlToDidAddress(baseUrl),
153
155
  paths: webvhPathsForPico(picoId),
@@ -0,0 +1,115 @@
1
+ "use strict";
2
+ /**
3
+ * did:webvh log update for portable move (Phase D, pico-move).
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.relocateWebvhDid = relocateWebvhDid;
7
+ exports.webvhScidFromStore = webvhScidFromStore;
8
+ exports.assertWebvhScidUnchanged = assertWebvhScidUnchanged;
9
+ const errors_1 = require("./errors");
10
+ const webvh_1 = require("./webvh");
11
+ const webvhCrypto_1 = require("./webvhCrypto");
12
+ function scidFromLog(log) {
13
+ var _a;
14
+ const params = (_a = log[0]) === null || _a === void 0 ? void 0 : _a.parameters;
15
+ const scid = params === null || params === void 0 ? void 0 : params.scid;
16
+ if (typeof scid !== "string" || scid.length === 0) {
17
+ throw new errors_1.IdentityError("webvh log missing SCID", 500);
18
+ }
19
+ return scid;
20
+ }
21
+ /** Append a portable log entry for a new host/path or DIDComm endpoint. */
22
+ async function relocateWebvhDid(store, pf, getBaseUrl, picoId, options = {}) {
23
+ const priorDid = await store.getWebvhDid(picoId);
24
+ const log = await store.getWebvhLog(picoId);
25
+ const rawKeys = await store.getWebvhKeys(picoId);
26
+ if (!priorDid || !(log === null || log === void 0 ? void 0 : log.length) || !rawKeys) {
27
+ throw new errors_1.IdentityError(`Pico ${picoId} has no did:webvh to relocate`, 404);
28
+ }
29
+ const keyMaterial = (0, webvh_1.keysFromStore)(rawKeys);
30
+ if (!keyMaterial) {
31
+ throw new errors_1.IdentityError(`Pico ${picoId} webvh keys are invalid`, 500);
32
+ }
33
+ const baseUrl = options.baseUrl || getBaseUrl();
34
+ if (!baseUrl) {
35
+ throw new errors_1.IdentityError("Engine base_url is required to relocate did:webvh", 500);
36
+ }
37
+ const priorScid = scidFromLog(log);
38
+ const crypto = await (0, webvhCrypto_1.createWebvhCrypto)(keyMaterial);
39
+ const verifier = await (0, webvhCrypto_1.createPassthroughVerifier)();
40
+ let ingressEci = await store.getDidcommIngressEci(picoId);
41
+ if (options.renewIngress || !ingressEci) {
42
+ if (options.renewIngress && ingressEci) {
43
+ await store.putDidcommIngressEci(picoId, "");
44
+ }
45
+ ingressEci = await (0, webvh_1.ensureDidcommIngress)(store, pf, picoId, baseUrl);
46
+ }
47
+ const webvh = await (0, webvhCrypto_1.loadDidWebvhTs)();
48
+ const updated = await webvh.updateDID({
49
+ log: log,
50
+ signer: crypto,
51
+ verifier,
52
+ updateKeys: [keyMaterial.updateKeyMultibase],
53
+ verificationMethods: [keyMaterial.verificationMethod],
54
+ address: (0, webvh_1.baseUrlToDidAddress)(baseUrl),
55
+ paths: options.paths || (0, webvh_1.webvhPathsForPico)(picoId),
56
+ services: [
57
+ {
58
+ id: "#didcomm",
59
+ type: "DIDCommMessaging",
60
+ serviceEndpoint: (0, webvh_1.didcommServiceEndpoint)(baseUrl, ingressEci),
61
+ accept: ["didcomm/v2"],
62
+ },
63
+ ],
64
+ });
65
+ const newDid = updated.did;
66
+ const newScid = updated.meta.scid;
67
+ if (newScid !== priorScid) {
68
+ throw new errors_1.IdentityError(`webvh SCID changed during relocation (${priorScid} → ${newScid})`, 500);
69
+ }
70
+ await store.putWebvhDid(picoId, newDid);
71
+ await store.putWebvhLog(picoId, updated.log);
72
+ if (updated.webDoc) {
73
+ await store.putWebvhWebDoc(picoId, updated.webDoc);
74
+ }
75
+ await store.putDidDoc(picoId, {
76
+ did: newDid,
77
+ doc: updated.doc,
78
+ cachedAt: new Date().toISOString(),
79
+ });
80
+ const endpoint = (0, webvh_1.didcommServiceEndpoint)(baseUrl, ingressEci);
81
+ return {
82
+ priorDid,
83
+ newDid,
84
+ scid: newScid,
85
+ didcommEndpoint: endpoint,
86
+ };
87
+ }
88
+ /** Resolve SCID from a stored log (for tests and verification). */
89
+ async function webvhScidFromStore(store, picoId) {
90
+ const log = await store.getWebvhLog(picoId);
91
+ if (!(log === null || log === void 0 ? void 0 : log.length)) {
92
+ return null;
93
+ }
94
+ try {
95
+ return scidFromLog(log);
96
+ }
97
+ catch (_a) {
98
+ return null;
99
+ }
100
+ }
101
+ /** Verify local log resolves and SCID matches expectation. */
102
+ async function assertWebvhScidUnchanged(store, picoId, expectedScid) {
103
+ const log = await store.getWebvhLog(picoId);
104
+ if (!(log === null || log === void 0 ? void 0 : log.length)) {
105
+ throw new errors_1.IdentityError("Missing webvh log", 404);
106
+ }
107
+ const resolved = await (0, webvh_1.resolveLocalWebvhLog)(log);
108
+ const scid = scidFromLog(log);
109
+ if (scid !== expectedScid) {
110
+ throw new errors_1.IdentityError(`SCID mismatch: ${scid} !== ${expectedScid}`, 500);
111
+ }
112
+ if (resolved.did !== (await store.getWebvhDid(picoId))) {
113
+ throw new errors_1.IdentityError("Resolved DID does not match stored DID", 500);
114
+ }
115
+ }
package/dist/index.js CHANGED
@@ -13,26 +13,50 @@ const logging_1 = require("./logging");
13
13
  const levelDb_1 = require("./levelDb");
14
14
  const provisionRoot_1 = require("./provisionRoot");
15
15
  const RulesetRegistryLoaderFs_1 = require("./RulesetRegistryLoaderFs");
16
+ const bundledKrl_1 = require("./bundledKrl");
17
+ const subtreeWrangler_1 = require("./subtreeWrangler");
16
18
  const server_1 = require("./server");
19
+ const engineConfig_1 = require("./engineConfig");
17
20
  const charwise = require("charwise");
18
21
  const safeJsonCodec = require("level-json-coerce-null");
19
- const homeDir = require("home-dir");
20
22
  const version = require("../package.json").version;
23
+ /** Integration harnesses (e.g. manifold-api Docker tests): boot with one root, no passkey. */
24
+ function autoCreateRootFromEnv() {
25
+ const v = process.env.PICO_ENGINE_AUTO_CREATE_ROOT;
26
+ if (typeof v !== "string" || v.trim().length === 0) {
27
+ return undefined;
28
+ }
29
+ const s = v.trim().toLowerCase();
30
+ if (s === "1" || s === "true" || s === "yes") {
31
+ return true;
32
+ }
33
+ if (s === "0" || s === "false" || s === "no") {
34
+ return false;
35
+ }
36
+ return undefined;
37
+ }
21
38
  async function startEngine(configuration = {}) {
22
- var _a, _b;
23
- let home = configuration.home;
24
- let port = configuration.port;
25
- let base_url = configuration.base_url;
26
- if (typeof home !== "string") {
27
- const envHome = process.env.PICO_ENGINE_HOME;
28
- if (typeof envHome === "string" &&
29
- envHome.length > 0 &&
30
- process.env.NODE_ENV === "test") {
31
- home = envHome;
32
- }
33
- else {
34
- home = homeDir(".pico-engine");
35
- }
39
+ var _a, _b, _c, _d, _e, _f, _g;
40
+ const settings = (0, engineConfig_1.resolveEngineSettings)({
41
+ home: configuration.home,
42
+ port: configuration.port,
43
+ base_url: configuration.base_url,
44
+ rpID: configuration.rpID,
45
+ rpName: configuration.rpName,
46
+ origin: configuration.origin,
47
+ allowSelfSignup: configuration.allowSelfSignup,
48
+ defaultRootPolicyCeiling: configuration.defaultRootPolicyCeiling,
49
+ globalEventDeny: configuration.globalEventDeny,
50
+ globalQueryDeny: configuration.globalQueryDeny,
51
+ });
52
+ (0, engineConfig_1.installEngineRuntimeSettings)(settings);
53
+ const home = settings.home;
54
+ let port = (_a = configuration.port) !== null && _a !== void 0 ? _a : settings.port;
55
+ const baseUrlFromCaller = configuration.base_url;
56
+ /** Filled after listen when using port 0 or when config baseUrl port does not match. */
57
+ let base_url = baseUrlFromCaller;
58
+ if (base_url == null && port > 0) {
59
+ base_url = settings.baseUrl;
36
60
  }
37
61
  await makeDir(home);
38
62
  const logFilePath = (0, logging_1.resolveEngineLogFilePath)(home);
@@ -50,7 +74,10 @@ async function startEngine(configuration = {}) {
50
74
  log,
51
75
  modules: configuration.modules,
52
76
  useEventInputTime: configuration.useEventInputTime,
53
- autoCreateRootPico: (_a = configuration.autoCreateRootPico) !== null && _a !== void 0 ? _a : false,
77
+ autoCreateRootPico: (_c = (_b = configuration.autoCreateRootPico) !== null && _b !== void 0 ? _b : autoCreateRootFromEnv()) !== null && _c !== void 0 ? _c : false,
78
+ defaultRootPolicyCeiling: (_d = configuration.defaultRootPolicyCeiling) !== null && _d !== void 0 ? _d : settings.defaultRootPolicyCeiling,
79
+ globalEventDeny: (_e = configuration.globalEventDeny) !== null && _e !== void 0 ? _e : settings.globalEventDeny,
80
+ globalQueryDeny: (_f = configuration.globalQueryDeny) !== null && _f !== void 0 ? _f : settings.globalQueryDeny,
54
81
  getPicoLogs(picoId) {
55
82
  if (!logFilePath) {
56
83
  return Promise.resolve([]);
@@ -59,18 +86,46 @@ async function startEngine(configuration = {}) {
59
86
  },
60
87
  });
61
88
  const pf = core.picoFramework;
89
+ core.resolveBundledRulesetUrl = bundledKrl_1.resolveBundledKrlUrl;
90
+ core.subtreeImportServices = (0, subtreeWrangler_1.wranglerSubtreeImportServices)(core.rsRegistry);
62
91
  const identity = new identity_1.IdentityStore({ db: pf.db });
63
92
  let identityService;
93
+ const onPicoCreated = async (picoId, ctx) => {
94
+ if (core.base_url) {
95
+ await identityService.ensureWebvhDid(picoId, { isRoot: ctx.isRoot });
96
+ }
97
+ };
64
98
  identityService = new identity_1.IdentityService({
65
99
  store: identity,
66
100
  getBaseUrl: () => core.base_url || base_url || "",
67
101
  pf,
102
+ rsRegistry: core.rsRegistry,
103
+ resolveBundledRulesetUrl: bundledKrl_1.resolveBundledKrlUrl,
104
+ reloadImportedSchedules: (picoIds) => core.reloadImportedSchedules(picoIds),
105
+ firePicoImported: async (result) => {
106
+ const importedRoot = pf.getPico(result.newRootPicoId);
107
+ if (!importedRoot) {
108
+ return;
109
+ }
110
+ await importedRoot.event({
111
+ eci: result.newRootEci,
112
+ domain: "wrangler",
113
+ name: "pico_imported",
114
+ data: {
115
+ attrs: {
116
+ oldRootPicoId: result.oldRootPicoId,
117
+ newRootPicoId: result.newRootPicoId,
118
+ eciMap: result.eciMap,
119
+ picoIdMap: result.picoIdMap,
120
+ portableIdentity: true,
121
+ },
122
+ },
123
+ time: Date.now(),
124
+ });
125
+ },
68
126
  });
69
- core.onPicoCreated = async (picoId, ctx) => {
70
- if (core.base_url) {
71
- await identityService.ensureWebvhDid(picoId, { isRoot: ctx.isRoot });
72
- }
73
- };
127
+ core.onPicoCreated = onPicoCreated;
128
+ core.subtreePortableHooks = (0, identity_1.createSubtreePortableHooks)(identity, pf);
74
129
  core.modules["dido"] = (0, identity_1.initDidoModule)(identityService);
75
130
  try {
76
131
  await core.start();
@@ -97,7 +152,7 @@ async function startEngine(configuration = {}) {
97
152
  rpID: configuration.rpID,
98
153
  rpName: configuration.rpName,
99
154
  origin: configuration.origin,
100
- allowSelfSignup: (_b = configuration.allowSelfSignup) !== null && _b !== void 0 ? _b : false,
155
+ allowSelfSignup: (_g = configuration.allowSelfSignup) !== null && _g !== void 0 ? _g : settings.allowSelfSignup,
101
156
  flushBootstrapUrl: async (url) => {
102
157
  const flushed = await rsRegistry.flush(url);
103
158
  return { rid: flushed.rid };
@@ -157,6 +212,10 @@ async function startEngine(configuration = {}) {
157
212
  if (typeof base_url !== "string") {
158
213
  base_url = `http://localhost:${port}`;
159
214
  }
215
+ else if (baseUrlFromCaller == null &&
216
+ (configuration.port === 0 || port !== settings.port)) {
217
+ base_url = `http://localhost:${port}`;
218
+ }
160
219
  core.base_url = base_url;
161
220
  await identityService.ensureWebvhForAllLoadedPicos();
162
221
  log.info(`Listening at ${base_url}`);
@@ -195,6 +254,7 @@ async function startEngine(configuration = {}) {
195
254
  port,
196
255
  base_url,
197
256
  pf,
257
+ core,
198
258
  uiECI,
199
259
  rsRegistry,
200
260
  auth,
package/dist/logging.js CHANGED
@@ -15,6 +15,7 @@ const fs = require("fs");
15
15
  const readline = require("readline");
16
16
  const krl_stdlib_1 = require("krl-stdlib");
17
17
  const path = require("path");
18
+ const engineConfig_1 = require("./engineConfig");
18
19
  const rfs = require("rotating-file-stream");
19
20
  const logStreams = {};
20
21
  function stdoutOnlyLogWriter() {
@@ -48,15 +49,12 @@ function getRotatingFileStream(filePath) {
48
49
  return logStreams[filePath];
49
50
  }
50
51
  function resolveEngineLogFilePath(home) {
51
- const configured = process.env.PICO_ENGINE_LOG_FILE;
52
- if (configured === "0" ||
53
- configured === "-" ||
54
- configured === "stdout" ||
55
- configured === "") {
52
+ const settings = (0, engineConfig_1.getEngineRuntimeSettings)();
53
+ if (settings.logToStdout) {
56
54
  return null;
57
55
  }
58
- if (typeof configured === "string" && configured.length > 0) {
59
- return path.resolve(configured);
56
+ if (settings.logFile) {
57
+ return settings.logFile;
60
58
  }
61
59
  return path.resolve(home, "pico-engine.log");
62
60
  }
@@ -95,10 +93,8 @@ async function getPicoLogs(filePath, picoId) {
95
93
  _c = rl_1_1.value;
96
94
  _d = false;
97
95
  const line = _c;
98
- // Each line in the readline input will be successively available here as
99
- // `line`.
100
96
  if (line.indexOf(picoId) < 0) {
101
- continue; // not my pico
97
+ continue;
102
98
  }
103
99
  let entry;
104
100
  try {
@@ -106,11 +102,11 @@ async function getPicoLogs(filePath, picoId) {
106
102
  }
107
103
  catch (err) { }
108
104
  if (!entry || entry.picoId !== picoId) {
109
- continue; // not my pico
105
+ continue;
110
106
  }
111
107
  const time = new Date(entry.time);
112
108
  if (Date.now() - time.getTime() > 1000 * 60 * 60 * 12) {
113
- continue; // too old
109
+ continue;
114
110
  }
115
111
  const out = Object.assign(Object.assign({}, entry), { level: krl_stdlib_1.krlLogLevelCodeToHuman[entry.level] || `${entry.level}`, time: entry.time, txnId: entry.txnId });
116
112
  delete out.picoId;