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,200 @@
1
+ import { ed25519 } from "@noble/curves/ed25519.js";
2
+ import {
3
+ bytesToHex,
4
+ convertEd25519PrivateKeyToX25519,
5
+ convertEd25519PublicKeyToX25519,
6
+ } from "@veramo/utils";
7
+ import type {
8
+ SignableDocument,
9
+ SigningInput,
10
+ SigningOutput,
11
+ VerificationMethod,
12
+ Verifier,
13
+ } from "didwebvh-ts/dist/types/interfaces";
14
+
15
+ type DidWebvhTs = typeof import("didwebvh-ts");
16
+
17
+ export interface StoredWebvhKeyMaterial {
18
+ updateKeyMultibase: string;
19
+ verificationMethodId: string;
20
+ verificationMethod: VerificationMethod & { secretKeyMultibase: string };
21
+ }
22
+
23
+ export async function generateWebvhKeyMaterial(): Promise<StoredWebvhKeyMaterial> {
24
+ const webvh = await loadDidWebvhTs();
25
+ const { secretKey, publicKey } = ed25519.keygen();
26
+ const publicKeyMultibase = webvh.multibaseEncode(
27
+ new Uint8Array([0xed, 0x01, ...publicKey]),
28
+ webvh.MultibaseEncoding.BASE58_BTC
29
+ );
30
+ const secretKeyMultibase = webvh.multibaseEncode(
31
+ new Uint8Array([0x80, 0x26, ...secretKey, ...publicKey]),
32
+ webvh.MultibaseEncoding.BASE58_BTC
33
+ );
34
+ const verificationMethodId = `did:key:${publicKeyMultibase}#${publicKeyMultibase}`;
35
+ return {
36
+ updateKeyMultibase: publicKeyMultibase,
37
+ verificationMethodId,
38
+ verificationMethod: {
39
+ type: "Multikey",
40
+ publicKeyMultibase,
41
+ secretKeyMultibase,
42
+ purpose: "assertionMethod",
43
+ },
44
+ };
45
+ }
46
+
47
+ export async function createWebvhCrypto(
48
+ keys: StoredWebvhKeyMaterial
49
+ ): Promise<WebvhCrypto> {
50
+ const webvh = await loadDidWebvhTs();
51
+ return new WebvhCrypto(webvh, keys);
52
+ }
53
+
54
+ export class WebvhCrypto {
55
+ private webvh: DidWebvhTs;
56
+ readonly keys: StoredWebvhKeyMaterial;
57
+
58
+ constructor(webvh: DidWebvhTs, keys: StoredWebvhKeyMaterial) {
59
+ this.webvh = webvh;
60
+ this.keys = keys;
61
+ }
62
+
63
+ getVerificationMethodId(): string {
64
+ return this.keys.verificationMethodId;
65
+ }
66
+
67
+ async sign(input: SigningInput<SignableDocument>): Promise<SigningOutput> {
68
+ const { bytes: secretKeyBytes } = this.webvh.multibaseDecode(
69
+ this.keys.verificationMethod.secretKeyMultibase
70
+ );
71
+ const seed = secretKeyBytes.slice(2).slice(0, 32);
72
+ const proof = ed25519.sign(
73
+ await this.webvh.prepareDataForSigning(input.document, input.proof),
74
+ seed
75
+ );
76
+ return {
77
+ proofValue: this.webvh.multibaseEncode(
78
+ proof,
79
+ this.webvh.MultibaseEncoding.BASE58_BTC
80
+ ),
81
+ };
82
+ }
83
+
84
+ async verify(
85
+ signature: Uint8Array,
86
+ message: Uint8Array,
87
+ publicKey: Uint8Array
88
+ ): Promise<boolean> {
89
+ return ed25519.verify(signature, message, publicKey, { zip215: false });
90
+ }
91
+ }
92
+
93
+ export function storedKeysFromWebvhKeys(
94
+ raw: Record<string, unknown>
95
+ ): StoredWebvhKeyMaterial | null {
96
+ const updateKeyMultibase = raw.updateKeyMultibase;
97
+ const verificationMethodId = raw.verificationMethodId;
98
+ const verificationMethod = raw.verificationMethod;
99
+ if (
100
+ typeof updateKeyMultibase !== "string" ||
101
+ typeof verificationMethodId !== "string" ||
102
+ !verificationMethod ||
103
+ typeof verificationMethod !== "object"
104
+ ) {
105
+ return null;
106
+ }
107
+ const vm = verificationMethod as VerificationMethod & {
108
+ secretKeyMultibase?: string;
109
+ };
110
+ if (typeof vm.secretKeyMultibase !== "string") {
111
+ return null;
112
+ }
113
+ return {
114
+ updateKeyMultibase,
115
+ verificationMethodId,
116
+ verificationMethod: vm as StoredWebvhKeyMaterial["verificationMethod"],
117
+ };
118
+ }
119
+
120
+ export function webvhKeysToStore(keys: StoredWebvhKeyMaterial): Record<string, unknown> {
121
+ return {
122
+ updateKeyMultibase: keys.updateKeyMultibase,
123
+ verificationMethodId: keys.verificationMethodId,
124
+ verificationMethod: keys.verificationMethod,
125
+ };
126
+ }
127
+
128
+ /** Veramo key material for decrypting DIDComm addressed to this pico's did:webvh. */
129
+ export async function webvhAgreementKeysForVeramo(
130
+ did: string,
131
+ doc: Record<string, unknown>,
132
+ keys: StoredWebvhKeyMaterial
133
+ ): Promise<
134
+ Array<{
135
+ type: string;
136
+ kid: string;
137
+ privateKeyHex: string;
138
+ publicKeyHex: string;
139
+ kms: string;
140
+ }>
141
+ > {
142
+ const webvh = await loadDidWebvhTs();
143
+ const { bytes: secretKeyBytes } = webvh.multibaseDecode(
144
+ keys.verificationMethod.secretKeyMultibase
145
+ );
146
+ const seed = secretKeyBytes.slice(2, 34);
147
+ const { bytes: publicKeyBytes } = webvh.multibaseDecode(
148
+ keys.verificationMethod.publicKeyMultibase as string
149
+ );
150
+ const edPub = publicKeyBytes.slice(2);
151
+ const xPub = convertEd25519PublicKeyToX25519(edPub);
152
+ const xPriv = convertEd25519PrivateKeyToX25519(seed);
153
+
154
+ const keyAgreement = doc.keyAgreement;
155
+ const kids: string[] = [];
156
+ if (Array.isArray(keyAgreement)) {
157
+ for (const entry of keyAgreement) {
158
+ if (typeof entry === "string") {
159
+ kids.push(entry);
160
+ } else if (entry && typeof entry === "object" && typeof (entry as { id?: string }).id === "string") {
161
+ kids.push((entry as { id: string }).id);
162
+ }
163
+ }
164
+ }
165
+ if (kids.length === 0) {
166
+ kids.push(`${did}#didcomm`);
167
+ }
168
+
169
+ return kids.map((kid) => ({
170
+ type: "X25519",
171
+ kid,
172
+ privateKeyHex: bytesToHex(xPriv),
173
+ publicKeyHex: bytesToHex(xPub),
174
+ kms: "local",
175
+ }));
176
+ }
177
+
178
+ let didWebvhTs: DidWebvhTs | undefined;
179
+
180
+ export async function loadDidWebvhTs(): Promise<DidWebvhTs> {
181
+ if (!didWebvhTs) {
182
+ didWebvhTs = await import("didwebvh-ts");
183
+ }
184
+ return didWebvhTs;
185
+ }
186
+
187
+ export type WebvhVerifier = Verifier;
188
+
189
+ export async function createPassthroughVerifier(): Promise<Verifier> {
190
+ return {
191
+ async verify(
192
+ signature: Uint8Array,
193
+ message: Uint8Array,
194
+ publicKey: Uint8Array
195
+ ): Promise<boolean> {
196
+ const { ed25519 } = await import("@noble/curves/ed25519.js");
197
+ return ed25519.verify(signature, message, publicKey, { zip215: false });
198
+ },
199
+ };
200
+ }
@@ -0,0 +1,64 @@
1
+ import { Express, Request, Response } from "express";
2
+ import { IdentityService } from "./IdentityService";
3
+ import { resolveLocalWebvhLog } from "./webvh";
4
+ import { IdentityError } from "./errors";
5
+
6
+ export function registerWebvhRoutes(
7
+ app: Express,
8
+ identity: IdentityService
9
+ ): void {
10
+ app.get("/identity/resolve", async (req: Request, res: Response) => {
11
+ try {
12
+ const did = String(req.query.did || "").trim();
13
+ if (!did) {
14
+ res.status(400).json({ error: "Missing did query parameter" });
15
+ return;
16
+ }
17
+ const doc = await identity.resolveDid("", did);
18
+ res.json({ did, didDocument: doc });
19
+ } catch (err) {
20
+ sendIdentityError(res, err);
21
+ }
22
+ });
23
+
24
+ app.get("/picos/:picoId/did.jsonl", async (req: Request, res: Response) => {
25
+ try {
26
+ const picoId = decodeURIComponent(req.params.picoId);
27
+ const jsonl = await identity.getWebvhLogJsonl(picoId);
28
+ if (!jsonl) {
29
+ res.status(404).send("Not found");
30
+ return;
31
+ }
32
+ const log = jsonl
33
+ .trim()
34
+ .split("\n")
35
+ .map((line) => JSON.parse(line));
36
+ await resolveLocalWebvhLog(log);
37
+ res.type("application/jsonld+json").send(jsonl);
38
+ } catch (err) {
39
+ sendIdentityError(res, err);
40
+ }
41
+ });
42
+
43
+ app.get("/picos/:picoId/did.json", async (req: Request, res: Response) => {
44
+ try {
45
+ const picoId = decodeURIComponent(req.params.picoId);
46
+ const doc = await identity.getParallelWebDoc(picoId);
47
+ if (!doc) {
48
+ res.status(404).send("Not found");
49
+ return;
50
+ }
51
+ res.json(doc);
52
+ } catch (err) {
53
+ sendIdentityError(res, err);
54
+ }
55
+ });
56
+ }
57
+
58
+ function sendIdentityError(res: Response, err: unknown): void {
59
+ if (err instanceof IdentityError) {
60
+ res.status(err.statusCode).json({ error: err.message });
61
+ return;
62
+ }
63
+ res.status(500).json({ error: (err as Error).message || "Internal error" });
64
+ }
package/src/index.ts CHANGED
@@ -6,6 +6,8 @@ import * as path from "path";
6
6
  import { PicoEngineCore, RulesetRegistry } from "pico-engine-core";
7
7
  import { PicoDbKey, PicoFramework } from "pico-framework";
8
8
  import { AuthService, WebAuthnAdapter, makeWebAuthnAdapter } from "./auth";
9
+ import { IdentityStore, IdentityService, initDidoModule } from "./identity";
10
+ import { registerWebvhRoutes } from "./identity/webvhRoutes";
9
11
  import { OAuthService, initOAuthModule } from "./oauth";
10
12
  import { getPicoLogs, makeRotatingFileLogWriter } from "./logging";
11
13
  import { provisionRoot, uiECIForRoot } from "./provisionRoot";
@@ -107,6 +109,8 @@ export interface PicoEngine {
107
109
  rsRegistry: RulesetRegistry;
108
110
  auth: AuthService;
109
111
  oauth: OAuthService;
112
+ identity: IdentityStore;
113
+ identityService: IdentityService;
110
114
  }
111
115
 
112
116
  export async function startEngine(
@@ -149,9 +153,23 @@ export async function startEngine(
149
153
  return getPicoLogs(logFilePath, picoId);
150
154
  },
151
155
  });
156
+ const pf = core.picoFramework;
157
+ const identity = new IdentityStore({ db: pf.db });
158
+ let identityService!: IdentityService;
159
+ identityService = new IdentityService({
160
+ store: identity,
161
+ getBaseUrl: () => core.base_url || base_url || "",
162
+ pf,
163
+ });
164
+ core.onPicoCreated = async (picoId, ctx) => {
165
+ if (core.base_url) {
166
+ await identityService.ensureWebvhDid(picoId, { isRoot: ctx.isRoot });
167
+ }
168
+ };
169
+ core.modules["dido"] = initDidoModule(identityService);
170
+
152
171
  await core.start();
153
172
  const rsRegistry = core.rsRegistry;
154
- const pf = core.picoFramework;
155
173
 
156
174
  // Fresh engines boot with zero roots. Adopt + (re)provision only when roots
157
175
  // already exist (test harness with autoCreateRootPico, or a migrated DB).
@@ -170,8 +188,15 @@ export async function startEngine(
170
188
  rpName: configuration.rpName,
171
189
  origin: configuration.origin,
172
190
  allowSelfSignup: configuration.allowSelfSignup ?? false,
191
+ flushBootstrapUrl: async (url) => {
192
+ const flushed = await rsRegistry.flush(url);
193
+ return { rid: flushed.rid };
194
+ },
173
195
  provisionRoot: async (opts) => {
174
196
  const { root, uiECI } = await provisionRoot(pf, core, opts);
197
+ if (core.base_url) {
198
+ await identityService.ensureWebvhDid(root.id, { isRoot: true });
199
+ }
175
200
  return { rootPicoId: root.id, uiECI };
176
201
  },
177
202
  getUiECI: (rootPicoId: string) => uiECIForRoot(pf, rootPicoId),
@@ -203,7 +228,7 @@ export async function startEngine(
203
228
  });
204
229
  core.modules["oauth"] = initOAuthModule(oauth);
205
230
 
206
- const app = server(core, uiECI, auth, oauth);
231
+ const app = server(core, uiECI, auth, oauth, identityService);
207
232
 
208
233
  if ((!port || !_.isInteger(port) || port < 1) && port !== 0) {
209
234
  port = process.env.NODE_ENV === "test" ? 0 : 3000;
@@ -225,6 +250,8 @@ export async function startEngine(
225
250
  }
226
251
  core.base_url = base_url;
227
252
 
253
+ await identityService.ensureWebvhForAllLoadedPicos();
254
+
228
255
  log.info(`Listening at ${base_url}`);
229
256
 
230
257
  if (uiECI) {
@@ -251,5 +278,7 @@ export async function startEngine(
251
278
  rsRegistry,
252
279
  auth,
253
280
  oauth,
281
+ identity,
282
+ identityService,
254
283
  };
255
284
  }
@@ -232,6 +232,17 @@ export class OAuthService {
232
232
  }
233
233
 
234
234
  async skyRequiresBearer(eci: string): Promise<boolean> {
235
+ try {
236
+ const channel = this.lookupChannelReadOnly(eci);
237
+ if (
238
+ channel.tags.includes("didcomm") &&
239
+ channel.tags.includes("ingress")
240
+ ) {
241
+ return false;
242
+ }
243
+ } catch (_e) {
244
+ // channel not found — fall through
245
+ }
235
246
  if (await this.channelRequiresBearer(eci)) {
236
247
  return true;
237
248
  }
@@ -242,6 +253,31 @@ export class OAuthService {
242
253
  return this.validateSkyBearerToken(token, channelEci);
243
254
  }
244
255
 
256
+ /** Mesh-wide OAuth token (authorization_code grant) → root pico id. */
257
+ async resolveMeshBearerToken(
258
+ token: string
259
+ ): Promise<{ rootPicoId: string; scope?: string } | null> {
260
+ const trimmed = (token || "").trim();
261
+ if (!trimmed) {
262
+ return null;
263
+ }
264
+ const record = await this.getTokenRecord(trimmed);
265
+ if (!record) {
266
+ return null;
267
+ }
268
+ if (record.expiresAt !== 0 && record.expiresAt < Date.now()) {
269
+ await this.deps.db.del([OAUTH_TOKEN_PREFIX, trimmed]);
270
+ return null;
271
+ }
272
+ if ((record.grant || "client_credentials") !== "authorization_code") {
273
+ return null;
274
+ }
275
+ if (!record.rootPicoId) {
276
+ return null;
277
+ }
278
+ return { rootPicoId: record.rootPicoId, scope: record.scope };
279
+ }
280
+
245
281
  async validateSkyBearerToken(
246
282
  token: string,
247
283
  channelEci: string
@@ -1,26 +1,30 @@
1
1
  import * as path from "path";
2
2
  import { PicoEngineCore } from "pico-engine-core";
3
- import { Pico, PicoFramework } from "pico-framework";
3
+ import { ChannelConfig, Pico, PicoFramework } from "pico-framework";
4
+ import {
5
+ UI_CHANNEL_EVENT_POLICY,
6
+ UI_CHANNEL_QUERY_POLICY,
7
+ UI_CHANNEL_TAGS,
8
+ } from "./uiChannelPolicies";
4
9
  import { toFileUrl } from "./utils/toFileUrl";
10
+ import { BUNDLED_KRL_FILES } from "./bundledKrl";
5
11
 
6
12
  /**
7
13
  * Base rulesets installed onto every root pico. These make up the engine's
8
14
  * "OS" layer (wrangler + friends) plus the built-in UI ruleset.
9
15
  */
10
- const BASE_KRL_FILES = [
11
- "io.picolabs.pico-engine-ui.krl",
12
- "io.picolabs.wrangler.krl",
13
- "io.picolabs.subscription.krl",
14
- "io.picolabs.did-o.krl",
15
- "io.picolabs.pds.krl",
16
- ];
17
-
18
- const UI_CHANNEL_TAGS = ["engine", "ui"];
16
+ const BASE_KRL_FILES = [...BUNDLED_KRL_FILES];
19
17
 
20
18
  function uiChannelKey(tags: string[]): string {
21
19
  return tags.slice(0).sort().join(",");
22
20
  }
23
21
 
22
+ const UI_CHANNEL_CONFIG: ChannelConfig = {
23
+ tags: [...UI_CHANNEL_TAGS],
24
+ eventPolicy: UI_CHANNEL_EVENT_POLICY,
25
+ queryPolicy: UI_CHANNEL_QUERY_POLICY,
26
+ };
27
+
24
28
  /**
25
29
  * Find the ["engine","ui"] channel on a pico, if it exists.
26
30
  */
@@ -32,12 +36,47 @@ export function uiECIForRoot(
32
36
  if (!pico) {
33
37
  return null;
34
38
  }
39
+ return uiECIForPico(pico);
40
+ }
41
+
42
+ export function uiECIForPico(pico: Pico): string | null {
35
43
  const chann = pico
36
44
  .toReadOnly()
37
- .channels.find((c) => uiChannelKey(UI_CHANNEL_TAGS) === uiChannelKey(c.tags));
45
+ .channels.find((c) => uiChannelKey([...UI_CHANNEL_TAGS]) === uiChannelKey(c.tags));
38
46
  return chann ? chann.id : null;
39
47
  }
40
48
 
49
+ async function forEachLoadedPico(
50
+ pf: PicoFramework,
51
+ fn: (pico: Pico) => Promise<void>
52
+ ): Promise<void> {
53
+ for (const pico of pf.loadedPicos()) {
54
+ await fn(pico);
55
+ }
56
+ }
57
+
58
+ /**
59
+ * Install the current io.picolabs.pico-engine-ui ruleset on every pico and
60
+ * refresh its ["engine","ui"] channel policy directly (no event policy gate).
61
+ */
62
+ export async function refreshAllUiChannelPolicies(
63
+ pf: PicoFramework,
64
+ core: PicoEngineCore
65
+ ): Promise<void> {
66
+ const uiUrl = toFileUrl(
67
+ path.resolve(__dirname, "..", "krl", "io.picolabs.pico-engine-ui.krl")
68
+ );
69
+ const { ruleset: uiRuleset } = await core.rsRegistry.flush(uiUrl);
70
+
71
+ await forEachLoadedPico(pf, async (pico) => {
72
+ await pico.install(uiRuleset, { url: uiUrl, config: {} });
73
+ const uiEci = uiECIForPico(pico);
74
+ if (uiEci) {
75
+ await pico.putChannel(uiEci, UI_CHANNEL_CONFIG);
76
+ }
77
+ });
78
+ }
79
+
41
80
  /**
42
81
  * Provision a root pico: install the base rulesets, ensure the ["engine","ui"]
43
82
  * channel exists, fire `engine_ui setup`, and return the root + its UI ECI.
@@ -49,7 +88,7 @@ export function uiECIForRoot(
49
88
  export async function provisionRoot(
50
89
  pf: PicoFramework,
51
90
  core: PicoEngineCore,
52
- opts: { root?: Pico; name?: string } = {}
91
+ opts: { root?: Pico; name?: string; bootstrapUrl?: string } = {}
53
92
  ): Promise<{ root: Pico; uiECI: string }> {
54
93
  const root = opts.root || (await pf.createRootPico());
55
94
 
@@ -61,11 +100,11 @@ export async function provisionRoot(
61
100
 
62
101
  let uiChannel = root
63
102
  .toReadOnly()
64
- .channels.find((c) => uiChannelKey(UI_CHANNEL_TAGS) === uiChannelKey(c.tags));
103
+ .channels.find((c) => uiChannelKey([...UI_CHANNEL_TAGS]) === uiChannelKey(c.tags));
65
104
  if (!uiChannel) {
66
105
  uiChannel = (
67
106
  await root.newChannel({
68
- tags: UI_CHANNEL_TAGS,
107
+ tags: [...UI_CHANNEL_TAGS],
69
108
  eventPolicy: {
70
109
  allow: [{ domain: "engine_ui", name: "setup" }],
71
110
  deny: [],
@@ -74,13 +113,20 @@ export async function provisionRoot(
74
113
  ).toReadOnly();
75
114
  }
76
115
 
77
- await pf.eventWait({
78
- eci: uiChannel.id,
79
- domain: "engine_ui",
80
- name: "setup",
81
- data: { attrs: {} },
82
- time: 0,
83
- });
116
+ await refreshAllUiChannelPolicies(pf, core);
117
+
118
+ const bootstrapUrl = (opts.bootstrapUrl || "").trim();
119
+ if (bootstrapUrl) {
120
+ // Same path as the Rulesets tab: engine_ui install → wrangler
121
+ // install_ruleset_request → ruleset_installed (bootstrap rulesets depend on this).
122
+ await pf.eventWait({
123
+ eci: uiChannel.id,
124
+ domain: "engine_ui",
125
+ name: "install",
126
+ data: { attrs: { url: bootstrapUrl, config: {} } },
127
+ time: 0,
128
+ });
129
+ }
84
130
 
85
131
  const name = (opts.name || "").trim();
86
132
  if (name) {
@@ -93,5 +139,13 @@ export async function provisionRoot(
93
139
  });
94
140
  }
95
141
 
142
+ await pf.eventWait({
143
+ eci: uiChannel.id,
144
+ domain: "engine_ui",
145
+ name: "setup",
146
+ data: { attrs: {} },
147
+ time: 0,
148
+ });
149
+
96
150
  return { root, uiECI: uiChannel.id };
97
151
  }
package/src/server.ts CHANGED
@@ -8,6 +8,10 @@ import { PicoEngineCore } from "pico-engine-core";
8
8
  import { PicoFramework } from "pico-framework";
9
9
  import { AuthError, AuthService } from "./auth";
10
10
  import { OAuthError, OAuthService, parseApproveBody, parseAuthorizeQuery, renderConsentHtml } from "./oauth";
11
+ import { uiECIForRoot } from "./provisionRoot";
12
+ import { IdentityService } from "./identity/IdentityService";
13
+ import { registerWebvhRoutes } from "./identity/webvhRoutes";
14
+ import { registerDidcommIngressRoutes } from "./identity/didcommIngressRoutes";
11
15
 
12
16
  const engineVersion = require("../package.json").version;
13
17
 
@@ -66,7 +70,8 @@ export function server(
66
70
  core: PicoEngineCore,
67
71
  uiECI: string | null,
68
72
  auth?: AuthService,
69
- oauth?: OAuthService
73
+ oauth?: OAuthService,
74
+ identity?: IdentityService
70
75
  ): Express {
71
76
  const pf = core.picoFramework;
72
77
  const app = express();
@@ -112,12 +117,18 @@ export function server(
112
117
  return defaultHelmet(req, res, next);
113
118
  });
114
119
  app.use(express.static(path.resolve(__dirname, "..", "public")));
120
+
121
+ if (identity) {
122
+ registerWebvhRoutes(app, identity);
123
+ }
124
+
115
125
  app.use(
116
126
  bodyParser.json({
117
127
  type: [
118
128
  "application/json",
119
129
  "application/octet-stream",
120
130
  "application/ssi-agent-wire",
131
+ "application/didcomm-encrypted+json",
121
132
  ],
122
133
  })
123
134
  );
@@ -129,6 +140,10 @@ export function server(
129
140
  })
130
141
  );
131
142
 
143
+ if (identity) {
144
+ registerDidcommIngressRoutes(app, identity);
145
+ }
146
+
132
147
  if (auth) {
133
148
  registerAuthRoutes(app, auth);
134
149
  }
@@ -239,6 +254,47 @@ export function server(
239
254
  registerOAuthRoutes(app, oauth, auth, requireAuthSession, parseCookies);
240
255
  }
241
256
 
257
+ app.get("/api/mesh-context", function (req, res, next) {
258
+ if (!oauth) {
259
+ res.status(503).json({ error: "OAuth not enabled" });
260
+ return;
261
+ }
262
+ const header = req.headers.authorization;
263
+ if (typeof header !== "string" || !header.startsWith("Bearer ")) {
264
+ res.status(401).json({ error: "Bearer token required" });
265
+ return;
266
+ }
267
+ const token = header.slice("Bearer ".length).trim();
268
+ oauth
269
+ .resolveMeshBearerToken(token)
270
+ .then((ctx) => {
271
+ if (!ctx) {
272
+ res.status(401).json({ error: "Invalid or expired token" });
273
+ return;
274
+ }
275
+ const rootUiEci = uiECIForRoot(pf, ctx.rootPicoId);
276
+ if (!rootUiEci) {
277
+ res.status(503).json({ error: "Mesh UI channel not found" });
278
+ return;
279
+ }
280
+ let baseUrl = core.base_url;
281
+ if (!baseUrl) {
282
+ baseUrl = `${req.protocol}://${req.get("host") || "localhost"}`;
283
+ }
284
+ baseUrl = baseUrl.replace(/\/$/, "");
285
+ res.json({
286
+ baseUrl,
287
+ rootUiEci,
288
+ oauth: {
289
+ authorize: `${baseUrl}/oauth/authorize`,
290
+ token: `${baseUrl}/oauth/token`,
291
+ },
292
+ scope: ctx.scope,
293
+ });
294
+ })
295
+ .catch(next);
296
+ });
297
+
242
298
  app.get("/api/ui-context", function (req, res, next) {
243
299
  const hasRoots = pf.rootPicos().length > 0;
244
300
  const base: any = {
@@ -687,6 +743,7 @@ function registerAuthRoutes(app: Express, auth: AuthService) {
687
743
  .createInvite({
688
744
  createdByAccountId: session.accountId,
689
745
  label: req.body && req.body.label,
746
+ bootstrapUrl: req.body && req.body.bootstrapUrl,
690
747
  })
691
748
  .then((invite) => res.json(invite))
692
749
  .catch(next);