pico-engine 1.6.2 → 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 (107) hide show
  1. package/README.md +117 -14
  2. package/dist/RulesetRegistryLoaderFs.js +24 -8
  3. package/dist/auth/cookies.js +32 -0
  4. package/dist/auth/index.js +6 -1
  5. package/dist/bundledKrl.js +129 -11
  6. package/dist/channelIdentityPolicy.js +22 -0
  7. package/dist/cli.js +105 -46
  8. package/dist/engineConfig.js +280 -0
  9. package/dist/identity/IdentityService.js +90 -0
  10. package/dist/identity/crossPico.js +106 -30
  11. package/dist/identity/didoModule.js +80 -18
  12. package/dist/identity/establishSubscription.js +2 -2
  13. package/dist/identity/identityPortable.js +92 -0
  14. package/dist/identity/index.js +10 -1
  15. package/dist/identity/localPeerReconcile.js +65 -0
  16. package/dist/identity/peerDid4.js +175 -0
  17. package/dist/identity/peerDid4Create.js +90 -0
  18. package/dist/identity/portableExportPrepare.js +196 -0
  19. package/dist/identity/portableMove.js +87 -0
  20. package/dist/identity/skyIntro.js +10 -4
  21. package/dist/identity/skyProtocol.js +26 -1
  22. package/dist/identity/skyRotation.js +121 -0
  23. package/dist/identity/store.js +5 -1
  24. package/dist/identity/subscriptionEntSync.js +72 -0
  25. package/dist/identity/veramoDidComm.js +41 -2
  26. package/dist/identity/webvh.js +4 -2
  27. package/dist/identity/webvhRelocation.js +115 -0
  28. package/dist/index.js +127 -34
  29. package/dist/levelDb.js +102 -0
  30. package/dist/logging.js +47 -8
  31. package/dist/oauth/OAuthService.js +12 -5
  32. package/dist/oauth/channelEligibility.js +7 -1
  33. package/dist/oauth/index.js +3 -1
  34. package/dist/policyConfigFromJson.js +112 -0
  35. package/dist/runMcp.js +27 -0
  36. package/dist/server.js +95 -24
  37. package/dist/subtreeWrangler.js +180 -0
  38. package/dist/uiChannelPolicies.js +16 -0
  39. package/krl/io.picolabs.oauth.krl +51 -5
  40. package/krl/io.picolabs.pds.krl +131 -10
  41. package/krl/io.picolabs.pico-engine-ui.krl +219 -22
  42. package/krl/io.picolabs.portable_subtree.krl +97 -0
  43. package/krl/io.picolabs.subscription.krl +226 -72
  44. package/krl/io.picolabs.wrangler.krl +300 -58
  45. package/mcp/devResources.js +118 -0
  46. package/mcp/devTools.js +351 -0
  47. package/mcp/engineClient.js +133 -0
  48. package/mcp/meshHttp.js +137 -0
  49. package/mcp/meshTools.js +189 -0
  50. package/mcp/runStdio.js +34 -0
  51. package/mcp/schemaToZod.js +56 -0
  52. package/package.json +22 -8
  53. package/public/docs/_sidebar.md +2 -1
  54. package/public/docs/llms-full.txt +479 -0
  55. package/public/docs/llms.txt +37 -0
  56. package/public/docs/openapi.yaml +78 -0
  57. package/public/docs/pico-engine.md +235 -4
  58. package/public/docs/pico-overview.md +117 -0
  59. package/public/docs/pico.md +3 -1
  60. package/public/docs/rulesets/README.md +25 -0
  61. package/public/docs/rulesets/io.picolabs.oauth.md +71 -0
  62. package/public/docs/rulesets/io.picolabs.pds.md +327 -0
  63. package/public/docs/rulesets/io.picolabs.pico-engine-ui.md +65 -0
  64. package/public/docs/rulesets/io.picolabs.portable_subtree.md +94 -0
  65. package/public/docs/rulesets/io.picolabs.subscription.md +398 -0
  66. package/public/docs/rulesets/io.picolabs.wrangler.md +471 -0
  67. package/public/pico-engine-ui.css +1 -1
  68. package/public/pico-engine-ui.js +28 -26
  69. package/src/RulesetRegistryLoaderFs.ts +43 -11
  70. package/src/auth/cookies.ts +34 -0
  71. package/src/auth/index.ts +7 -0
  72. package/src/bundledKrl.ts +150 -12
  73. package/src/channelIdentityPolicy.ts +29 -0
  74. package/src/cli.ts +98 -40
  75. package/src/engineConfig.ts +345 -0
  76. package/src/identity/IdentityService.ts +189 -1
  77. package/src/identity/crossPico.ts +161 -41
  78. package/src/identity/didoModule.ts +140 -23
  79. package/src/identity/establishSubscription.ts +2 -2
  80. package/src/identity/identityPortable.ts +153 -0
  81. package/src/identity/index.ts +14 -0
  82. package/src/identity/localPeerReconcile.ts +97 -0
  83. package/src/identity/peerDid4.ts +197 -0
  84. package/src/identity/peerDid4Create.ts +121 -0
  85. package/src/identity/portableExportPrepare.ts +302 -0
  86. package/src/identity/portableMove.ts +193 -0
  87. package/src/identity/skyIntro.ts +16 -12
  88. package/src/identity/skyProtocol.ts +46 -0
  89. package/src/identity/skyRotation.ts +211 -0
  90. package/src/identity/store.ts +5 -1
  91. package/src/identity/subscriptionEntSync.ts +97 -0
  92. package/src/identity/veramoDidComm.ts +52 -2
  93. package/src/identity/webvh.ts +4 -4
  94. package/src/identity/webvhRelocation.ts +167 -0
  95. package/src/index.ts +179 -39
  96. package/src/levelDb.ts +122 -0
  97. package/src/logging.ts +63 -11
  98. package/src/oauth/OAuthService.ts +20 -6
  99. package/src/oauth/channelEligibility.ts +9 -0
  100. package/src/oauth/index.ts +7 -1
  101. package/src/policyConfigFromJson.ts +131 -0
  102. package/src/runMcp.ts +30 -0
  103. package/src/server.ts +133 -27
  104. package/src/subtreeWrangler.ts +278 -0
  105. package/src/uiChannelPolicies.ts +16 -0
  106. package/krl/io.picolabs.did-o.krl +0 -349
  107. package/krl/test/didtestdid.krl +0 -78
@@ -5,10 +5,13 @@ import * as makeDir from "make-dir";
5
5
  import * as path from "path";
6
6
  import { RulesetRegistryLoader } from "pico-engine-core";
7
7
  import { PicoDbKey, Ruleset } from "pico-framework";
8
+ import type { KrlLogger } from "krl-stdlib";
8
9
  import * as urlLib from "url";
9
10
  import { resolveBundledKrlUrl } from "./bundledKrl";
11
+ import { openClassicLevelWithRecovery } from "./levelDb";
10
12
  const krlCompiler = require("krl-compiler");
11
13
  const krlCompilerVersion = require("krl-compiler/package.json").version;
14
+ const rulesetCompileGeneration = require("krl-compiler/src/rulesetCompileGeneration");
12
15
  const charwise = require("charwise");
13
16
  const safeJsonCodec = require("level-json-coerce-null");
14
17
 
@@ -31,18 +34,33 @@ interface DbUrlRuleset {
31
34
  compiler: {
32
35
  version: string;
33
36
  warnings: any[];
37
+ compileGeneration?: string;
34
38
  };
35
39
  }
36
40
 
37
- export function RulesetRegistryLoaderFs(
38
- engineHomeDir: string
39
- ): RulesetRegistryLoader {
41
+ function compileGenerationDir(): string {
42
+ return rulesetCompileGeneration().replace(/[^a-zA-Z0-9._-]+/g, "_");
43
+ }
44
+
45
+ export interface RulesetRegistryLoaderFsHandle {
46
+ loader: RulesetRegistryLoader;
47
+ close: () => Promise<void>;
48
+ }
49
+
50
+ export async function createRulesetRegistryLoaderFs(
51
+ engineHomeDir: string,
52
+ log?: KrlLogger
53
+ ): Promise<RulesetRegistryLoaderFsHandle> {
40
54
  const rulesetDir = path.resolve(engineHomeDir, "rulesets");
41
55
 
42
- const db = new ClassicLevel<PicoDbKey, any>(path.resolve(engineHomeDir, "rulesets-db"), {
43
- keyEncoding: charwise,
44
- valueEncoding: safeJsonCodec,
45
- })
56
+ const db = await openClassicLevelWithRecovery<PicoDbKey, any>(
57
+ path.resolve(engineHomeDir, "rulesets-db"),
58
+ {
59
+ keyEncoding: charwise,
60
+ valueEncoding: safeJsonCodec,
61
+ },
62
+ log
63
+ );
46
64
 
47
65
  async function compileAndLoad(
48
66
  url: string,
@@ -50,11 +68,11 @@ export function RulesetRegistryLoaderFs(
50
68
  hash: string
51
69
  ): Promise<{
52
70
  ruleset: Ruleset;
53
- compiler: { version: string; warnings: any[] };
71
+ compiler: DbUrlRuleset["compiler"];
54
72
  }> {
55
73
  const jsFile = path.resolve(
56
74
  rulesetDir,
57
- krlCompilerVersion,
75
+ compileGenerationDir(),
58
76
  hash.substr(0, 2),
59
77
  hash.substr(2, 2),
60
78
  hash + ".js"
@@ -85,15 +103,24 @@ export function RulesetRegistryLoaderFs(
85
103
 
86
104
  const ruleset: Ruleset = require(jsFile);
87
105
 
106
+ const compileGeneration = rulesetCompileGeneration();
88
107
  return {
89
108
  ruleset,
90
- compiler: { version: krlCompilerVersion, warnings: compileWarnings },
109
+ compiler: {
110
+ version: krlCompilerVersion,
111
+ warnings: compileWarnings,
112
+ compileGeneration,
113
+ },
91
114
  };
92
115
  }
93
116
 
94
- return {
117
+ const loader: RulesetRegistryLoader = {
95
118
  fetchKrl,
96
119
 
120
+ getCompileGeneration() {
121
+ return rulesetCompileGeneration();
122
+ },
123
+
97
124
  async save({ ruleset, ...rest }) {
98
125
  let toWrite: DbUrlRuleset = rest;
99
126
  await db.put(["url", toWrite.url], toWrite);
@@ -125,6 +152,11 @@ export function RulesetRegistryLoaderFs(
125
152
  };
126
153
  },
127
154
  };
155
+
156
+ return {
157
+ loader,
158
+ close: () => db.close(),
159
+ };
128
160
  }
129
161
 
130
162
  async function fetchKrl(url: string): Promise<string> {
@@ -0,0 +1,34 @@
1
+ export const DEFAULT_SESSION_COOKIE = "pico-session";
2
+ export const DEFAULT_CEREMONY_COOKIE = "pico-ceremony";
3
+
4
+ export interface AuthCookieNames {
5
+ session: string;
6
+ ceremony: string;
7
+ }
8
+
9
+ /** Session/ceremony cookie names scoped by port on local dev hosts. */
10
+ export function authCookieNames(origin: string): AuthCookieNames {
11
+ try {
12
+ const url = new URL(origin);
13
+ const local =
14
+ url.hostname === "localhost" ||
15
+ url.hostname === "127.0.0.1" ||
16
+ url.hostname.endsWith(".localhost");
17
+ if (local && url.port) {
18
+ return {
19
+ session: `${DEFAULT_SESSION_COOKIE}-${url.port}`,
20
+ ceremony: `${DEFAULT_CEREMONY_COOKIE}-${url.port}`,
21
+ };
22
+ }
23
+ } catch (_e) {
24
+ // fall through
25
+ }
26
+ return {
27
+ session: DEFAULT_SESSION_COOKIE,
28
+ ceremony: DEFAULT_CEREMONY_COOKIE,
29
+ };
30
+ }
31
+
32
+ export function sessionCookieHeader(origin: string, token: string): string {
33
+ return `${authCookieNames(origin).session}=${token}`;
34
+ }
package/src/auth/index.ts CHANGED
@@ -15,3 +15,10 @@ export {
15
15
  VerifiedAuthentication,
16
16
  makeWebAuthnAdapter,
17
17
  } from "./webauthn";
18
+ export {
19
+ authCookieNames,
20
+ sessionCookieHeader,
21
+ DEFAULT_SESSION_COOKIE,
22
+ DEFAULT_CEREMONY_COOKIE,
23
+ type AuthCookieNames,
24
+ } from "./cookies";
package/src/bundledKrl.ts CHANGED
@@ -14,29 +14,167 @@ export const BUNDLED_KRL_FILES = [
14
14
  "io.picolabs.pds.krl",
15
15
  ];
16
16
 
17
+ /** Rulesets that only function when installed on the mesh root pico. */
18
+ export const ROOT_ONLY_RULESET_RIDS = new Set(["io.picolabs.oauth"]);
19
+
20
+ export interface EngineKrlSource {
21
+ rid: string;
22
+ filename: string;
23
+ relativePath: string;
24
+ url: string;
25
+ name?: string;
26
+ description?: string;
27
+ rootOnly?: boolean;
28
+ }
29
+
17
30
  export function bundledKrlDir(): string {
18
31
  return path.resolve(__dirname, "..", "krl");
19
32
  }
20
33
 
21
- export function resolveBundledKrlUrl(url: string): string {
22
- let filename: string | null = null;
23
- try {
24
- const parsed = new URL(url);
25
- if (parsed.protocol === "file:") {
26
- filename = path.basename(parsed.pathname);
34
+ function walkKrlFiles(dir: string, baseDir: string, out: string[]): void {
35
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
36
+ const fullPath = path.join(dir, entry.name);
37
+ if (entry.isDirectory()) {
38
+ walkKrlFiles(fullPath, baseDir, out);
39
+ continue;
40
+ }
41
+ if (entry.isFile() && entry.name.endsWith(".krl")) {
42
+ out.push(path.relative(baseDir, fullPath).split(path.sep).join("/"));
27
43
  }
44
+ }
45
+ }
46
+
47
+ /** All `.krl` files under the engine's shipped `krl/` directory. */
48
+ export function listEngineKrlRelativePaths(): string[] {
49
+ const root = bundledKrlDir();
50
+ if (!fs.existsSync(root)) {
51
+ return [];
52
+ }
53
+ const paths: string[] = [];
54
+ walkKrlFiles(root, root, paths);
55
+ return paths.sort();
56
+ }
57
+
58
+ function ridFromRelativePath(relativePath: string): string {
59
+ const basename = path.basename(relativePath, ".krl");
60
+ return basename;
61
+ }
62
+
63
+ function readKrlMeta(
64
+ filePath: string
65
+ ): Pick<EngineKrlSource, "rid" | "name" | "description"> {
66
+ const text = fs.readFileSync(filePath, { encoding: "utf8", flag: "r" }).slice(0, 4000);
67
+ const ridMatch = text.match(/^ruleset\s+(\S+)/m);
68
+ const nameMatch = text.match(/\bname\s+"([^"]+)"/);
69
+ let description: string | undefined;
70
+ const descQuoted = text.match(/\bdescription\s+"([^"]+)"/);
71
+ if (descQuoted) {
72
+ description = descQuoted[1];
73
+ } else {
74
+ const descHere = text.match(/\bdescription\s+<<\s*([\s\S]*?)\s*>>/);
75
+ if (descHere) {
76
+ description = descHere[1].replace(/\s+/g, " ").trim();
77
+ }
78
+ }
79
+ return {
80
+ rid: ridMatch ? ridMatch[1] : ridFromRelativePath(path.basename(filePath)),
81
+ name: nameMatch ? nameMatch[1] : undefined,
82
+ description,
83
+ };
84
+ }
85
+
86
+ export function engineKrlHttpPath(relativePath: string): string {
87
+ return `/krl/${relativePath.split(path.sep).join("/")}`;
88
+ }
89
+
90
+ export function engineKrlFileUrl(
91
+ relativePath: string,
92
+ baseUrl?: string
93
+ ): string {
94
+ if (baseUrl) {
95
+ return `${baseUrl.replace(/\/$/, "")}${engineKrlHttpPath(relativePath)}`;
96
+ }
97
+ return toFileUrl(path.join(bundledKrlDir(), relativePath));
98
+ }
99
+
100
+ export function listEngineKrlSources(baseUrl?: string): EngineKrlSource[] {
101
+ const root = bundledKrlDir();
102
+ return listEngineKrlRelativePaths().map((relativePath) => {
103
+ const filePath = path.join(root, relativePath);
104
+ const meta = readKrlMeta(filePath);
105
+ const filename = path.basename(relativePath);
106
+ return {
107
+ rid: meta.rid,
108
+ filename,
109
+ relativePath,
110
+ url: engineKrlFileUrl(relativePath, baseUrl),
111
+ name: meta.name,
112
+ description: meta.description,
113
+ rootOnly: ROOT_ONLY_RULESET_RIDS.has(meta.rid),
114
+ };
115
+ });
116
+ }
117
+
118
+ /** Map a URL to a relative path under `krl/`, if it refers to an engine-shipped ruleset. */
119
+ export function engineKrlRelativeFromUrl(url: string): string | null {
120
+ let parsed: URL;
121
+ try {
122
+ parsed = new URL(url);
28
123
  } catch {
29
- return url;
124
+ return null;
30
125
  }
31
126
 
32
- if (!filename || !BUNDLED_KRL_FILES.includes(filename)) {
33
- return url;
127
+ if (parsed.protocol === "file:") {
128
+ const filePath = decodeURI(parsed.pathname).replace(/^\/([a-z]:\/)/i, "$1");
129
+ const normalized = path.normalize(filePath);
130
+ const root = bundledKrlDir();
131
+ if (normalized.startsWith(root + path.sep) || normalized === root) {
132
+ return path.relative(root, normalized).split(path.sep).join("/");
133
+ }
134
+ const basename = path.basename(normalized);
135
+ const candidate = path.join(root, basename);
136
+ if (basename.endsWith(".krl") && fs.existsSync(candidate)) {
137
+ return basename;
138
+ }
139
+ return null;
34
140
  }
35
141
 
36
- const localPath = path.join(bundledKrlDir(), filename);
37
- if (fs.existsSync(localPath)) {
38
- return toFileUrl(localPath);
142
+ if (parsed.protocol === "http:" || parsed.protocol === "https:") {
143
+ const match = parsed.pathname.match(/^\/krl\/(.+\.krl)$/);
144
+ if (match) {
145
+ const relativePath = match[1].split("/").join(path.sep);
146
+ const candidate = path.join(bundledKrlDir(), relativePath);
147
+ if (fs.existsSync(candidate)) {
148
+ return match[1];
149
+ }
150
+ }
39
151
  }
40
152
 
153
+ return null;
154
+ }
155
+
156
+ export function resolveEngineKrlFile(relativePath: string): string | null {
157
+ const normalized = relativePath.split("/").join(path.sep);
158
+ const candidate = path.resolve(bundledKrlDir(), normalized);
159
+ const root = bundledKrlDir();
160
+ if (
161
+ candidate.startsWith(root + path.sep) &&
162
+ fs.existsSync(candidate) &&
163
+ candidate.endsWith(".krl")
164
+ ) {
165
+ return candidate;
166
+ }
167
+ return null;
168
+ }
169
+
170
+ export function resolveBundledKrlUrl(url: string): string {
171
+ const relativePath = engineKrlRelativeFromUrl(url);
172
+ if (!relativePath) {
173
+ return url;
174
+ }
175
+ const localPath = resolveEngineKrlFile(relativePath);
176
+ if (localPath) {
177
+ return toFileUrl(localPath);
178
+ }
41
179
  return url;
42
180
  }
@@ -0,0 +1,29 @@
1
+ import {
2
+ ChannelReadOnly,
3
+ hasUnrestrictedEventAllow,
4
+ hasUnrestrictedQueryAllow,
5
+ } from "pico-framework";
6
+
7
+ import { getEngineRuntimeSettings } from "./engineConfig";
8
+
9
+ /** See {@link EngineSettings.wildcardSkyRequireBearer} (config file or env). */
10
+ export function wildcardSkyRequireBearerEnabled(): boolean {
11
+ return getEngineRuntimeSettings().wildcardSkyRequireBearer;
12
+ }
13
+
14
+ /**
15
+ * True when the channel grants unrestricted events or queries (*.* allow rules).
16
+ * Such channels require an authenticated HTTP caller (OAuth bearer or /c/* session).
17
+ */
18
+ export function channelHasUnrestrictedAllow(channel: ChannelReadOnly): boolean {
19
+ return (
20
+ hasUnrestrictedEventAllow(channel.eventPolicy) ||
21
+ hasUnrestrictedQueryAllow(channel.queryPolicy)
22
+ );
23
+ }
24
+
25
+ export function isDidcommIngressChannel(channel: ChannelReadOnly): boolean {
26
+ return (
27
+ channel.tags.includes("didcomm") && channel.tags.includes("ingress")
28
+ );
29
+ }
package/src/cli.ts CHANGED
@@ -1,10 +1,42 @@
1
- import { PicoEngineConfiguration, startEngine } from "./index";
1
+ import { PicoEngine, PicoEngineConfiguration, startEngine } from "./index";
2
+ import { applyConfigCliArgs, resolveEngineSettings } from "./engineConfig";
2
3
  const version = require("../package.json").version;
3
4
 
5
+ let argv: string[];
6
+ try {
7
+ argv = applyConfigCliArgs(process.argv.slice(2));
8
+ } catch (err) {
9
+ console.error(err instanceof Error ? err.message : err);
10
+ process.exit(1);
11
+ }
12
+
13
+ if (argv[0] === "mcp") {
14
+ import("./runMcp")
15
+ .then(({ runMcpCli }) => runMcpCli(argv))
16
+ .catch((err) => {
17
+ console.error(err);
18
+ process.exit(1);
19
+ });
20
+ } else if (argv[0] === "config" && argv[1] === "path") {
21
+ const { resolveEngineConfigFilePath, defaultEngineConfigFilePath } =
22
+ require("./engineConfig");
23
+ const target = resolveEngineConfigFilePath();
24
+ console.log(target);
25
+ if (target === defaultEngineConfigFilePath()) {
26
+ console.error(
27
+ "(default; copy packages/pico-engine/config.example.json here to customize)",
28
+ );
29
+ }
30
+ process.exit(0);
31
+ } else {
32
+ startPicoEngineCli();
33
+ }
34
+
35
+ function startPicoEngineCli() {
4
36
  const args: {
5
37
  help: boolean;
6
38
  version: boolean;
7
- } = require("minimist")(process.argv.slice(2), {
39
+ } = require("minimist")(argv, {
8
40
  boolean: ["help", "version"],
9
41
  alias: {
10
42
  help: "h",
@@ -19,53 +51,79 @@ if (args.help) {
19
51
  console.log(`
20
52
  USAGE
21
53
 
22
- pico-engine [--version] [--help|-h]
54
+ pico-engine [--config|-c <path>] [--version] [--help|-h]
55
+ pico-engine [--config|-c <path>] config path
56
+ pico-engine [--config|-c <path>] mcp --stdio
57
+
58
+ Multiple engines on one machine: use a separate config file per process (unique
59
+ home, port, baseUrl). Examples: packages/pico-engine/config.instances.example/
60
+ and docker/config/ for compose.
61
+
62
+ Configuration (preferred):
23
63
 
24
- Environment Variables:
64
+ ~/.config/pico-engine/config.json
65
+ (or --config / PICO_ENGINE_CONFIG to another file path)
25
66
 
26
- PORT - The port the http server should listen on. By default it's 3000
27
- PICO_ENGINE_HOME - Where the database and other files should be stored. By default it's ~/.pico-engine/
28
- PICO_ENGINE_BASE_URL - The public url prefix to reach this engine. By default it's http://localhost:$PORT
29
- PICO_ENGINE_ALLOW_SELF_SIGNUP - Set to "true" or "1" to allow anyone to register a new account
30
- after the engine is bootstrapped. Default is false (login only; bootstrap and invite still work).
31
- PICO_ENGINE_ALLOW_LOCALHOST_C - Set to "0" to require passkey session on /c/* even from localhost.
32
- Default (unset) allows localhost without session for in-engine ctx:event HTTP loops. See MEMORY.md.
67
+ See packages/pico-engine/config.example.json (and config.policy-ceiling.example.json for 1.8 policy fields).
68
+ Precedence: defaults → environment variables → config file → tests/API overrides.
69
+ (Config file wins over PORT and PICO_ENGINE_HOME when both are set; env fills gaps the file omits.)
70
+
71
+ Environment (optional; Docker/CI when not set in config file):
72
+
73
+ PORT - HTTP listen port
74
+ PICO_ENGINE_CONFIG - Path to config JSON (default ~/.config/pico-engine/config.json)
75
+ PICO_ENGINE_HOME - Data directory (DB, ruleset cache); overridden by config "home" when present
76
+ PICO_ENGINE_BASE_URL - Public URL (WebAuthn, did:webvh)
77
+ PICO_ENGINE_RP_ID / PICO_ENGINE_ORIGIN - WebAuthn (or use webauthn block in config file)
78
+ PICO_ENGINE_ALLOW_SELF_SIGNUP - "true"/"1" or "false"/"0"
79
+ PICO_ENGINE_ALLOW_LOCALHOST_C - "0" disables localhost /c/* bypass (see config allowLocalhostChannelBypass)
80
+ PICO_ENGINE_WILDCARD_SKY_REQUIRE_BEARER - "1" enables wildcard /sky/* bearer requirement
81
+ PICO_ENGINE_LOG_FILE - Log path, or stdout/- / 0 for console only
33
82
  `);
34
83
  process.exit(0);
35
84
  }
36
85
 
37
- const env: PicoEngineConfiguration = {};
86
+ const settings = resolveEngineSettings({});
87
+ const env: PicoEngineConfiguration = {
88
+ home: settings.home,
89
+ port: settings.port,
90
+ base_url: settings.baseUrl,
91
+ rpID: settings.rpID,
92
+ rpName: settings.rpName,
93
+ origin: settings.origin,
94
+ allowSelfSignup: settings.allowSelfSignup,
95
+ };
38
96
 
39
- if (process.env.PORT) {
40
- const port = parseInt(process.env.PORT, 10);
41
- if (port > 0) {
42
- env.port = port;
43
- }
44
- }
97
+ function installGracefulShutdown(engine: PicoEngine) {
98
+ let shuttingDown = false;
45
99
 
46
- if (
47
- typeof process.env.PICO_ENGINE_HOME === "string" &&
48
- process.env.PICO_ENGINE_HOME.length > 0
49
- ) {
50
- env.home = process.env.PICO_ENGINE_HOME;
51
- }
100
+ const onSignal = (signal: NodeJS.Signals) => {
101
+ if (shuttingDown) {
102
+ return;
103
+ }
104
+ shuttingDown = true;
105
+ console.log(`Received ${signal}; shutting down`);
106
+ engine
107
+ .shutdown()
108
+ .then(() => process.exit(0))
109
+ .catch((err) => {
110
+ console.error("Shutdown failed.");
111
+ console.error(err);
112
+ process.exit(1);
113
+ });
114
+ };
52
115
 
53
- if (
54
- typeof process.env.PICO_ENGINE_BASE_URL === "string" &&
55
- process.env.PICO_ENGINE_BASE_URL.length > 0
56
- ) {
57
- env.base_url = process.env.PICO_ENGINE_BASE_URL;
116
+ process.on("SIGTERM", onSignal);
117
+ process.on("SIGINT", onSignal);
58
118
  }
59
119
 
60
- const allowSelfSignupEnv = process.env.PICO_ENGINE_ALLOW_SELF_SIGNUP;
61
- if (allowSelfSignupEnv === "true" || allowSelfSignupEnv === "1") {
62
- env.allowSelfSignup = true;
63
- } else if (allowSelfSignupEnv === "false" || allowSelfSignupEnv === "0") {
64
- env.allowSelfSignup = false;
120
+ startEngine(env)
121
+ .then((engine) => {
122
+ installGracefulShutdown(engine);
123
+ })
124
+ .catch((err) => {
125
+ console.error("Failed to start engine.");
126
+ console.error(err);
127
+ process.exit(1);
128
+ });
65
129
  }
66
-
67
- startEngine(env).catch((err) => {
68
- console.error("Failed to start engine.");
69
- console.error(err);
70
- process.exit(1);
71
- });