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
package/README.md CHANGED
@@ -4,6 +4,17 @@
4
4
 
5
5
  An implementation of the [pico-engine](http://www.windley.com/archives/2016/03/rebuilding_krl.shtml) hosted on node.js
6
6
 
7
+ ## Quick start
8
+
9
+ ```sh
10
+ npm install -g pico-engine
11
+ pico-engine
12
+ ```
13
+
14
+ Open `http://localhost:3000` — a root pico and UI channel are created on first run. Operator settings (port, data dir, policy ceiling) live in **`~/.config/pico-engine/config.json`**; copy [`config.example.json`](config.example.json). See [`public/docs/pico-engine.md`](public/docs/pico-engine.md).
15
+
16
+ **Agents (local dev):** [`CLAUDE.md`](../../CLAUDE.md) at repo root + `pico-engine mcp --stdio` (stdio MCP to the same engine). Machine-readable docs: [`public/docs/llms.txt`](public/docs/llms.txt).
17
+
7
18
  ## Getting Started
8
19
 
9
20
  ### Installing
@@ -148,7 +159,7 @@ The CLI handles **SIGTERM** and **SIGINT** by closing the HTTP server and both d
148
159
  ```yaml
149
160
  services:
150
161
  pico-engine:
151
- image: picolabs/pico-engine:1.6.4
162
+ image: picolabs/pico-engine:1.8.0
152
163
  ports:
153
164
  - "3001:3000"
154
165
  environment:
@@ -350,13 +361,7 @@ Authorization: Bearer oat_…
350
361
 
351
362
  ### Building the UI
352
363
 
353
- The root `npm run build` compiles the engine only. To pick up UI changes (Settings, Channels OAuth panels, etc.):
354
-
355
- ```sh
356
- cd packages/pico-engine-ui && npm run build
357
- ```
358
-
359
- That copies the bundle into `packages/pico-engine/public/`. Restart the engine and hard-refresh the browser.
364
+ Repo root `npm run build` includes the UI bundle (via `lerna run build`), copied into `packages/pico-engine/public/`. Restart the engine and hard-refresh the browser after a build.
360
365
 
361
366
  For UI development, run the engine and `npm run dev` in `packages/pico-engine-ui` in separate terminals.
362
367
 
@@ -21,6 +21,7 @@ const bundledKrl_1 = require("./bundledKrl");
21
21
  const levelDb_1 = require("./levelDb");
22
22
  const krlCompiler = require("krl-compiler");
23
23
  const krlCompilerVersion = require("krl-compiler/package.json").version;
24
+ const rulesetCompileGeneration = require("krl-compiler/src/rulesetCompileGeneration");
24
25
  const charwise = require("charwise");
25
26
  const safeJsonCodec = require("level-json-coerce-null");
26
27
  function getUrlFilename(url) {
@@ -33,6 +34,9 @@ function getUrlFilename(url) {
33
34
  catch (err) { }
34
35
  return null;
35
36
  }
37
+ function compileGenerationDir() {
38
+ return rulesetCompileGeneration().replace(/[^a-zA-Z0-9._-]+/g, "_");
39
+ }
36
40
  async function createRulesetRegistryLoaderFs(engineHomeDir, log) {
37
41
  const rulesetDir = path.resolve(engineHomeDir, "rulesets");
38
42
  const db = await (0, levelDb_1.openClassicLevelWithRecovery)(path.resolve(engineHomeDir, "rulesets-db"), {
@@ -40,7 +44,7 @@ async function createRulesetRegistryLoaderFs(engineHomeDir, log) {
40
44
  valueEncoding: safeJsonCodec,
41
45
  }, log);
42
46
  async function compileAndLoad(url, krl, hash) {
43
- const jsFile = path.resolve(rulesetDir, krlCompilerVersion, hash.substr(0, 2), hash.substr(2, 2), hash + ".js");
47
+ const jsFile = path.resolve(rulesetDir, compileGenerationDir(), hash.substr(0, 2), hash.substr(2, 2), hash + ".js");
44
48
  let compileWarnings = [];
45
49
  if (await fsExist(jsFile)) {
46
50
  // already compiled
@@ -62,13 +66,21 @@ async function createRulesetRegistryLoaderFs(engineHomeDir, log) {
62
66
  });
63
67
  }
64
68
  const ruleset = require(jsFile);
69
+ const compileGeneration = rulesetCompileGeneration();
65
70
  return {
66
71
  ruleset,
67
- compiler: { version: krlCompilerVersion, warnings: compileWarnings },
72
+ compiler: {
73
+ version: krlCompilerVersion,
74
+ warnings: compileWarnings,
75
+ compileGeneration,
76
+ },
68
77
  };
69
78
  }
70
79
  const loader = {
71
80
  fetchKrl,
81
+ getCompileGeneration() {
82
+ return rulesetCompileGeneration();
83
+ },
72
84
  async save(_a) {
73
85
  var { ruleset } = _a, rest = __rest(_a, ["ruleset"]);
74
86
  let toWrite = rest;
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_CEREMONY_COOKIE = exports.DEFAULT_SESSION_COOKIE = void 0;
4
+ exports.authCookieNames = authCookieNames;
5
+ exports.sessionCookieHeader = sessionCookieHeader;
6
+ exports.DEFAULT_SESSION_COOKIE = "pico-session";
7
+ exports.DEFAULT_CEREMONY_COOKIE = "pico-ceremony";
8
+ /** Session/ceremony cookie names scoped by port on local dev hosts. */
9
+ function authCookieNames(origin) {
10
+ try {
11
+ const url = new URL(origin);
12
+ const local = url.hostname === "localhost" ||
13
+ url.hostname === "127.0.0.1" ||
14
+ url.hostname.endsWith(".localhost");
15
+ if (local && url.port) {
16
+ return {
17
+ session: `${exports.DEFAULT_SESSION_COOKIE}-${url.port}`,
18
+ ceremony: `${exports.DEFAULT_CEREMONY_COOKIE}-${url.port}`,
19
+ };
20
+ }
21
+ }
22
+ catch (_e) {
23
+ // fall through
24
+ }
25
+ return {
26
+ session: exports.DEFAULT_SESSION_COOKIE,
27
+ ceremony: exports.DEFAULT_CEREMONY_COOKIE,
28
+ };
29
+ }
30
+ function sessionCookieHeader(origin, token) {
31
+ return `${authCookieNames(origin).session}=${token}`;
32
+ }
@@ -1,8 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.makeWebAuthnAdapter = exports.AuthError = exports.AuthService = void 0;
3
+ exports.DEFAULT_CEREMONY_COOKIE = exports.DEFAULT_SESSION_COOKIE = exports.sessionCookieHeader = exports.authCookieNames = exports.makeWebAuthnAdapter = exports.AuthError = exports.AuthService = void 0;
4
4
  var AuthService_1 = require("./AuthService");
5
5
  Object.defineProperty(exports, "AuthService", { enumerable: true, get: function () { return AuthService_1.AuthService; } });
6
6
  Object.defineProperty(exports, "AuthError", { enumerable: true, get: function () { return AuthService_1.AuthError; } });
7
7
  var webauthn_1 = require("./webauthn");
8
8
  Object.defineProperty(exports, "makeWebAuthnAdapter", { enumerable: true, get: function () { return webauthn_1.makeWebAuthnAdapter; } });
9
+ var cookies_1 = require("./cookies");
10
+ Object.defineProperty(exports, "authCookieNames", { enumerable: true, get: function () { return cookies_1.authCookieNames; } });
11
+ Object.defineProperty(exports, "sessionCookieHeader", { enumerable: true, get: function () { return cookies_1.sessionCookieHeader; } });
12
+ Object.defineProperty(exports, "DEFAULT_SESSION_COOKIE", { enumerable: true, get: function () { return cookies_1.DEFAULT_SESSION_COOKIE; } });
13
+ Object.defineProperty(exports, "DEFAULT_CEREMONY_COOKIE", { enumerable: true, get: function () { return cookies_1.DEFAULT_CEREMONY_COOKIE; } });
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.wildcardSkyRequireBearerEnabled = wildcardSkyRequireBearerEnabled;
4
+ exports.channelHasUnrestrictedAllow = channelHasUnrestrictedAllow;
5
+ exports.isDidcommIngressChannel = isDidcommIngressChannel;
6
+ const pico_framework_1 = require("pico-framework");
7
+ const engineConfig_1 = require("./engineConfig");
8
+ /** See {@link EngineSettings.wildcardSkyRequireBearer} (config file or env). */
9
+ function wildcardSkyRequireBearerEnabled() {
10
+ return (0, engineConfig_1.getEngineRuntimeSettings)().wildcardSkyRequireBearer;
11
+ }
12
+ /**
13
+ * True when the channel grants unrestricted events or queries (*.* allow rules).
14
+ * Such channels require an authenticated HTTP caller (OAuth bearer or /c/* session).
15
+ */
16
+ function channelHasUnrestrictedAllow(channel) {
17
+ return ((0, pico_framework_1.hasUnrestrictedEventAllow)(channel.eventPolicy) ||
18
+ (0, pico_framework_1.hasUnrestrictedQueryAllow)(channel.queryPolicy));
19
+ }
20
+ function isDidcommIngressChannel(channel) {
21
+ return (channel.tags.includes("didcomm") && channel.tags.includes("ingress"));
22
+ }
package/dist/cli.js CHANGED
@@ -1,83 +1,118 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const index_1 = require("./index");
4
+ const engineConfig_1 = require("./engineConfig");
4
5
  const version = require("../package.json").version;
5
- const args = require("minimist")(process.argv.slice(2), {
6
- boolean: ["help", "version"],
7
- alias: {
8
- help: "h",
9
- },
10
- });
11
- if (args.version) {
12
- console.log(version);
6
+ let argv;
7
+ try {
8
+ argv = (0, engineConfig_1.applyConfigCliArgs)(process.argv.slice(2));
9
+ }
10
+ catch (err) {
11
+ console.error(err instanceof Error ? err.message : err);
12
+ process.exit(1);
13
+ }
14
+ if (argv[0] === "mcp") {
15
+ Promise.resolve().then(() => require("./runMcp")).then(({ runMcpCli }) => runMcpCli(argv))
16
+ .catch((err) => {
17
+ console.error(err);
18
+ process.exit(1);
19
+ });
20
+ }
21
+ else if (argv[0] === "config" && argv[1] === "path") {
22
+ const { resolveEngineConfigFilePath, defaultEngineConfigFilePath } = require("./engineConfig");
23
+ const target = resolveEngineConfigFilePath();
24
+ console.log(target);
25
+ if (target === defaultEngineConfigFilePath()) {
26
+ console.error("(default; copy packages/pico-engine/config.example.json here to customize)");
27
+ }
13
28
  process.exit(0);
14
29
  }
15
- if (args.help) {
16
- console.log(`
30
+ else {
31
+ startPicoEngineCli();
32
+ }
33
+ function startPicoEngineCli() {
34
+ const args = require("minimist")(argv, {
35
+ boolean: ["help", "version"],
36
+ alias: {
37
+ help: "h",
38
+ },
39
+ });
40
+ if (args.version) {
41
+ console.log(version);
42
+ process.exit(0);
43
+ }
44
+ if (args.help) {
45
+ console.log(`
17
46
  USAGE
18
47
 
19
- pico-engine [--version] [--help|-h]
48
+ pico-engine [--config|-c <path>] [--version] [--help|-h]
49
+ pico-engine [--config|-c <path>] config path
50
+ pico-engine [--config|-c <path>] mcp --stdio
51
+
52
+ Multiple engines on one machine: use a separate config file per process (unique
53
+ home, port, baseUrl). Examples: packages/pico-engine/config.instances.example/
54
+ and docker/config/ for compose.
55
+
56
+ Configuration (preferred):
57
+
58
+ ~/.config/pico-engine/config.json
59
+ (or --config / PICO_ENGINE_CONFIG to another file path)
20
60
 
21
- Environment Variables:
61
+ See packages/pico-engine/config.example.json (and config.policy-ceiling.example.json for 1.8 policy fields).
62
+ Precedence: defaults → environment variables → config file → tests/API overrides.
63
+ (Config file wins over PORT and PICO_ENGINE_HOME when both are set; env fills gaps the file omits.)
22
64
 
23
- PORT - The port the http server should listen on. By default it's 3000
24
- PICO_ENGINE_HOME - Where the database and other files should be stored. By default it's ~/.pico-engine/
25
- PICO_ENGINE_BASE_URL - The public url prefix to reach this engine. By default it's http://localhost:$PORT
26
- PICO_ENGINE_ALLOW_SELF_SIGNUP - Set to "true" or "1" to allow anyone to register a new account
27
- after the engine is bootstrapped. Default is false (login only; bootstrap and invite still work).
28
- PICO_ENGINE_ALLOW_LOCALHOST_C - Set to "0" to require passkey session on /c/* even from localhost.
29
- Default (unset) allows localhost without session for in-engine ctx:event HTTP loops. See MEMORY.md.
65
+ Environment (optional; Docker/CI when not set in config file):
66
+
67
+ PORT - HTTP listen port
68
+ PICO_ENGINE_CONFIG - Path to config JSON (default ~/.config/pico-engine/config.json)
69
+ PICO_ENGINE_HOME - Data directory (DB, ruleset cache); overridden by config "home" when present
70
+ PICO_ENGINE_BASE_URL - Public URL (WebAuthn, did:webvh)
71
+ PICO_ENGINE_RP_ID / PICO_ENGINE_ORIGIN - WebAuthn (or use webauthn block in config file)
72
+ PICO_ENGINE_ALLOW_SELF_SIGNUP - "true"/"1" or "false"/"0"
73
+ PICO_ENGINE_ALLOW_LOCALHOST_C - "0" disables localhost /c/* bypass (see config allowLocalhostChannelBypass)
74
+ PICO_ENGINE_WILDCARD_SKY_REQUIRE_BEARER - "1" enables wildcard /sky/* bearer requirement
75
+ PICO_ENGINE_LOG_FILE - Log path, or stdout/- / 0 for console only
30
76
  `);
31
- process.exit(0);
32
- }
33
- const env = {};
34
- if (process.env.PORT) {
35
- const port = parseInt(process.env.PORT, 10);
36
- if (port > 0) {
37
- env.port = port;
77
+ process.exit(0);
38
78
  }
39
- }
40
- if (typeof process.env.PICO_ENGINE_HOME === "string" &&
41
- process.env.PICO_ENGINE_HOME.length > 0) {
42
- env.home = process.env.PICO_ENGINE_HOME;
43
- }
44
- if (typeof process.env.PICO_ENGINE_BASE_URL === "string" &&
45
- process.env.PICO_ENGINE_BASE_URL.length > 0) {
46
- env.base_url = process.env.PICO_ENGINE_BASE_URL;
47
- }
48
- const allowSelfSignupEnv = process.env.PICO_ENGINE_ALLOW_SELF_SIGNUP;
49
- if (allowSelfSignupEnv === "true" || allowSelfSignupEnv === "1") {
50
- env.allowSelfSignup = true;
51
- }
52
- else if (allowSelfSignupEnv === "false" || allowSelfSignupEnv === "0") {
53
- env.allowSelfSignup = false;
54
- }
55
- function installGracefulShutdown(engine) {
56
- let shuttingDown = false;
57
- const onSignal = (signal) => {
58
- if (shuttingDown) {
59
- return;
60
- }
61
- shuttingDown = true;
62
- console.log(`Received ${signal}; shutting down`);
63
- engine
64
- .shutdown()
65
- .then(() => process.exit(0))
66
- .catch((err) => {
67
- console.error("Shutdown failed.");
68
- console.error(err);
69
- process.exit(1);
70
- });
79
+ const settings = (0, engineConfig_1.resolveEngineSettings)({});
80
+ const env = {
81
+ home: settings.home,
82
+ port: settings.port,
83
+ base_url: settings.baseUrl,
84
+ rpID: settings.rpID,
85
+ rpName: settings.rpName,
86
+ origin: settings.origin,
87
+ allowSelfSignup: settings.allowSelfSignup,
71
88
  };
72
- process.on("SIGTERM", onSignal);
73
- process.on("SIGINT", onSignal);
89
+ function installGracefulShutdown(engine) {
90
+ let shuttingDown = false;
91
+ const onSignal = (signal) => {
92
+ if (shuttingDown) {
93
+ return;
94
+ }
95
+ shuttingDown = true;
96
+ console.log(`Received ${signal}; shutting down`);
97
+ engine
98
+ .shutdown()
99
+ .then(() => process.exit(0))
100
+ .catch((err) => {
101
+ console.error("Shutdown failed.");
102
+ console.error(err);
103
+ process.exit(1);
104
+ });
105
+ };
106
+ process.on("SIGTERM", onSignal);
107
+ process.on("SIGINT", onSignal);
108
+ }
109
+ (0, index_1.startEngine)(env)
110
+ .then((engine) => {
111
+ installGracefulShutdown(engine);
112
+ })
113
+ .catch((err) => {
114
+ console.error("Failed to start engine.");
115
+ console.error(err);
116
+ process.exit(1);
117
+ });
74
118
  }
75
- (0, index_1.startEngine)(env)
76
- .then((engine) => {
77
- installGracefulShutdown(engine);
78
- })
79
- .catch((err) => {
80
- console.error("Failed to start engine.");
81
- console.error(err);
82
- process.exit(1);
83
- });
@@ -0,0 +1,280 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.installEngineRuntimeSettings = installEngineRuntimeSettings;
4
+ exports.getEngineRuntimeSettings = getEngineRuntimeSettings;
5
+ exports.defaultEngineSettings = defaultEngineSettings;
6
+ exports.defaultEngineConfigFilePath = defaultEngineConfigFilePath;
7
+ exports.resolveEngineConfigFilePath = resolveEngineConfigFilePath;
8
+ exports.applyConfigCliArgs = applyConfigCliArgs;
9
+ exports.loadConfigFileSettings = loadConfigFileSettings;
10
+ exports.settingsFromEnv = settingsFromEnv;
11
+ exports.resolveEngineSettings = resolveEngineSettings;
12
+ const fs = require("fs");
13
+ const os = require("os");
14
+ const path = require("path");
15
+ const policyConfigFromJson_1 = require("./policyConfigFromJson");
16
+ const homeDir = require("home-dir");
17
+ let runtimeSettings = null;
18
+ function installEngineRuntimeSettings(settings) {
19
+ runtimeSettings = settings;
20
+ }
21
+ function getEngineRuntimeSettings() {
22
+ if (!runtimeSettings) {
23
+ runtimeSettings = defaultEngineSettings();
24
+ }
25
+ return runtimeSettings;
26
+ }
27
+ function defaultEngineSettings() {
28
+ return {
29
+ home: homeDir(".pico-engine"),
30
+ port: 3000,
31
+ baseUrl: "http://localhost:3000",
32
+ allowSelfSignup: false,
33
+ allowLocalhostChannelBypass: true,
34
+ wildcardSkyRequireBearer: false,
35
+ logToStdout: false,
36
+ };
37
+ }
38
+ function defaultEngineConfigFilePath() {
39
+ const xdg = process.env.XDG_CONFIG_HOME &&
40
+ process.env.XDG_CONFIG_HOME.trim().length > 0
41
+ ? process.env.XDG_CONFIG_HOME
42
+ : path.join(os.homedir(), ".config");
43
+ return path.join(xdg, "pico-engine", "config.json");
44
+ }
45
+ function resolveEngineConfigFilePath() {
46
+ const explicit = process.env.PICO_ENGINE_CONFIG;
47
+ if (typeof explicit === "string" && explicit.trim().length > 0) {
48
+ return path.resolve(expandHome(explicit.trim()));
49
+ }
50
+ return defaultEngineConfigFilePath();
51
+ }
52
+ /**
53
+ * Parse `--config` / `-c` from argv and set `PICO_ENGINE_CONFIG` before settings resolve.
54
+ * Use one config file per engine process (host or container).
55
+ */
56
+ function applyConfigCliArgs(argv) {
57
+ const out = [];
58
+ for (let i = 0; i < argv.length; i++) {
59
+ const arg = argv[i];
60
+ if (arg === "--config" || arg === "-c") {
61
+ const val = argv[++i];
62
+ if (typeof val !== "string" || val.length === 0) {
63
+ throw new Error(`${arg} requires a config file path`);
64
+ }
65
+ process.env.PICO_ENGINE_CONFIG = path.resolve(expandHome(val));
66
+ continue;
67
+ }
68
+ if (arg.startsWith("--config=")) {
69
+ const val = arg.slice("--config=".length);
70
+ if (val.length === 0) {
71
+ throw new Error("--config= requires a config file path");
72
+ }
73
+ process.env.PICO_ENGINE_CONFIG = path.resolve(expandHome(val));
74
+ continue;
75
+ }
76
+ out.push(arg);
77
+ }
78
+ return out;
79
+ }
80
+ function expandHome(p) {
81
+ if (p.startsWith("~/")) {
82
+ return path.join(os.homedir(), p.slice(2));
83
+ }
84
+ return p;
85
+ }
86
+ function parseConfigFile(raw) {
87
+ let data;
88
+ try {
89
+ data = JSON.parse(raw);
90
+ }
91
+ catch (err) {
92
+ throw new Error(`Invalid engine config JSON (${resolveEngineConfigFilePath()}): ${err}`);
93
+ }
94
+ if (!data || typeof data !== "object" || Array.isArray(data)) {
95
+ throw new Error("Engine config must be a JSON object");
96
+ }
97
+ const o = data;
98
+ const out = {};
99
+ if (typeof o.home === "string" && o.home.length > 0) {
100
+ out.home = expandHome(o.home);
101
+ }
102
+ if (typeof o.port === "number" && o.port >= 0) {
103
+ out.port = o.port;
104
+ }
105
+ if (typeof o.baseUrl === "string" && o.baseUrl.length > 0) {
106
+ out.baseUrl = o.baseUrl;
107
+ }
108
+ const webauthn = o.webauthn && typeof o.webauthn === "object" && !Array.isArray(o.webauthn)
109
+ ? o.webauthn
110
+ : null;
111
+ if (webauthn) {
112
+ if (typeof webauthn.rpId === "string")
113
+ out.rpID = webauthn.rpId;
114
+ if (typeof webauthn.rpName === "string")
115
+ out.rpName = webauthn.rpName;
116
+ if (typeof webauthn.origin === "string")
117
+ out.origin = webauthn.origin;
118
+ }
119
+ if (typeof o.rpID === "string")
120
+ out.rpID = o.rpID;
121
+ if (typeof o.rpName === "string")
122
+ out.rpName = o.rpName;
123
+ if (typeof o.origin === "string")
124
+ out.origin = o.origin;
125
+ if (typeof o.allowSelfSignup === "boolean") {
126
+ out.allowSelfSignup = o.allowSelfSignup;
127
+ }
128
+ if (typeof o.allowLocalhostChannelBypass === "boolean") {
129
+ out.allowLocalhostChannelBypass = o.allowLocalhostChannelBypass;
130
+ }
131
+ if (typeof o.wildcardSkyRequireBearer === "boolean") {
132
+ out.wildcardSkyRequireBearer = o.wildcardSkyRequireBearer;
133
+ }
134
+ if (typeof o.logToStdout === "boolean") {
135
+ out.logToStdout = o.logToStdout;
136
+ }
137
+ if (typeof o.logFile === "string" && o.logFile.length > 0) {
138
+ if (o.logFile === "stdout" || o.logFile === "-") {
139
+ out.logToStdout = true;
140
+ }
141
+ else {
142
+ out.logFile = path.resolve(expandHome(o.logFile));
143
+ }
144
+ }
145
+ const rootCeiling = (0, policyConfigFromJson_1.parsePolicyCeilingFromJson)(o.defaultRootPolicyCeiling, "defaultRootPolicyCeiling");
146
+ if (rootCeiling) {
147
+ out.defaultRootPolicyCeiling = rootCeiling;
148
+ }
149
+ const globalEventDeny = (0, policyConfigFromJson_1.parseGlobalEventDenyFromJson)(o.globalEventDeny);
150
+ if (globalEventDeny) {
151
+ out.globalEventDeny = globalEventDeny;
152
+ }
153
+ const globalQueryDeny = (0, policyConfigFromJson_1.parseGlobalQueryDenyFromJson)(o.globalQueryDeny);
154
+ if (globalQueryDeny) {
155
+ out.globalQueryDeny = globalQueryDeny;
156
+ }
157
+ return out;
158
+ }
159
+ function loadConfigFileSettings() {
160
+ if (process.env.NODE_ENV === "test" && !process.env.PICO_ENGINE_CONFIG) {
161
+ return {};
162
+ }
163
+ const filePath = resolveEngineConfigFilePath();
164
+ if (!fs.existsSync(filePath)) {
165
+ return {};
166
+ }
167
+ const raw = fs.readFileSync(filePath, "utf8");
168
+ return parseConfigFile(raw);
169
+ }
170
+ function parseBoolEnv(val) {
171
+ if (val === undefined)
172
+ return undefined;
173
+ if (val === "true" || val === "1")
174
+ return true;
175
+ if (val === "false" || val === "0")
176
+ return false;
177
+ return undefined;
178
+ }
179
+ function settingsFromEnv() {
180
+ const out = {};
181
+ if (process.env.PORT) {
182
+ const port = parseInt(process.env.PORT, 10);
183
+ if (port >= 0)
184
+ out.port = port;
185
+ }
186
+ if (typeof process.env.PICO_ENGINE_HOME === "string" &&
187
+ process.env.PICO_ENGINE_HOME.length > 0) {
188
+ out.home = expandHome(process.env.PICO_ENGINE_HOME);
189
+ }
190
+ if (typeof process.env.PICO_ENGINE_BASE_URL === "string" &&
191
+ process.env.PICO_ENGINE_BASE_URL.length > 0) {
192
+ out.baseUrl = process.env.PICO_ENGINE_BASE_URL;
193
+ }
194
+ if (typeof process.env.PICO_ENGINE_RP_ID === "string" &&
195
+ process.env.PICO_ENGINE_RP_ID.length > 0) {
196
+ out.rpID = process.env.PICO_ENGINE_RP_ID;
197
+ }
198
+ if (typeof process.env.PICO_ENGINE_ORIGIN === "string" &&
199
+ process.env.PICO_ENGINE_ORIGIN.length > 0) {
200
+ out.origin = process.env.PICO_ENGINE_ORIGIN;
201
+ }
202
+ const signup = parseBoolEnv(process.env.PICO_ENGINE_ALLOW_SELF_SIGNUP);
203
+ if (signup !== undefined)
204
+ out.allowSelfSignup = signup;
205
+ const localhostC = parseBoolEnv(process.env.PICO_ENGINE_ALLOW_LOCALHOST_C);
206
+ if (localhostC !== undefined) {
207
+ out.allowLocalhostChannelBypass = localhostC;
208
+ }
209
+ else if (process.env.PICO_ENGINE_ALLOW_LOCALHOST_C === "0") {
210
+ out.allowLocalhostChannelBypass = false;
211
+ }
212
+ const wildcard = parseBoolEnv(process.env.PICO_ENGINE_WILDCARD_SKY_REQUIRE_BEARER);
213
+ if (wildcard !== undefined)
214
+ out.wildcardSkyRequireBearer = wildcard;
215
+ const logFile = process.env.PICO_ENGINE_LOG_FILE;
216
+ if (logFile === "0" || logFile === "-" || logFile === "stdout" || logFile === "") {
217
+ out.logToStdout = true;
218
+ }
219
+ else if (typeof logFile === "string" && logFile.length > 0) {
220
+ out.logFile = path.resolve(expandHome(logFile));
221
+ }
222
+ return out;
223
+ }
224
+ function mergeSettings(base, ...layers) {
225
+ const merged = Object.assign({}, base);
226
+ for (const layer of layers) {
227
+ Object.assign(merged, layer);
228
+ }
229
+ return merged;
230
+ }
231
+ /**
232
+ * Resolve settings: defaults ← environment ← config file ← programmatic (tests, API).
233
+ * `PORT` and `PICO_ENGINE_HOME` (and other env keys) apply when the file omits them;
234
+ * values in the config file win when both are set.
235
+ */
236
+ function resolveEngineSettings(programmatic = {}) {
237
+ var _a;
238
+ const fromProgrammatic = {};
239
+ if (programmatic.home)
240
+ fromProgrammatic.home = programmatic.home;
241
+ if (programmatic.port != null)
242
+ fromProgrammatic.port = programmatic.port;
243
+ const baseUrl = (_a = programmatic.baseUrl) !== null && _a !== void 0 ? _a : programmatic.base_url;
244
+ if (baseUrl)
245
+ fromProgrammatic.baseUrl = baseUrl;
246
+ if (programmatic.rpID)
247
+ fromProgrammatic.rpID = programmatic.rpID;
248
+ if (programmatic.rpName)
249
+ fromProgrammatic.rpName = programmatic.rpName;
250
+ if (programmatic.origin)
251
+ fromProgrammatic.origin = programmatic.origin;
252
+ if (programmatic.allowSelfSignup !== undefined) {
253
+ fromProgrammatic.allowSelfSignup = programmatic.allowSelfSignup;
254
+ }
255
+ if (programmatic.allowLocalhostChannelBypass !== undefined) {
256
+ fromProgrammatic.allowLocalhostChannelBypass =
257
+ programmatic.allowLocalhostChannelBypass;
258
+ }
259
+ if (programmatic.wildcardSkyRequireBearer !== undefined) {
260
+ fromProgrammatic.wildcardSkyRequireBearer =
261
+ programmatic.wildcardSkyRequireBearer;
262
+ }
263
+ if (programmatic.logToStdout !== undefined) {
264
+ fromProgrammatic.logToStdout = programmatic.logToStdout;
265
+ }
266
+ if (programmatic.logFile !== undefined) {
267
+ fromProgrammatic.logFile = programmatic.logFile;
268
+ }
269
+ if (programmatic.defaultRootPolicyCeiling !== undefined) {
270
+ fromProgrammatic.defaultRootPolicyCeiling =
271
+ programmatic.defaultRootPolicyCeiling;
272
+ }
273
+ if (programmatic.globalEventDeny !== undefined) {
274
+ fromProgrammatic.globalEventDeny = programmatic.globalEventDeny;
275
+ }
276
+ if (programmatic.globalQueryDeny !== undefined) {
277
+ fromProgrammatic.globalQueryDeny = programmatic.globalQueryDeny;
278
+ }
279
+ return mergeSettings(defaultEngineSettings(), settingsFromEnv(), loadConfigFileSettings(), fromProgrammatic);
280
+ }