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
@@ -11,6 +11,7 @@ import { resolveBundledKrlUrl } from "./bundledKrl";
11
11
  import { openClassicLevelWithRecovery } from "./levelDb";
12
12
  const krlCompiler = require("krl-compiler");
13
13
  const krlCompilerVersion = require("krl-compiler/package.json").version;
14
+ const rulesetCompileGeneration = require("krl-compiler/src/rulesetCompileGeneration");
14
15
  const charwise = require("charwise");
15
16
  const safeJsonCodec = require("level-json-coerce-null");
16
17
 
@@ -33,9 +34,14 @@ interface DbUrlRuleset {
33
34
  compiler: {
34
35
  version: string;
35
36
  warnings: any[];
37
+ compileGeneration?: string;
36
38
  };
37
39
  }
38
40
 
41
+ function compileGenerationDir(): string {
42
+ return rulesetCompileGeneration().replace(/[^a-zA-Z0-9._-]+/g, "_");
43
+ }
44
+
39
45
  export interface RulesetRegistryLoaderFsHandle {
40
46
  loader: RulesetRegistryLoader;
41
47
  close: () => Promise<void>;
@@ -62,11 +68,11 @@ export async function createRulesetRegistryLoaderFs(
62
68
  hash: string
63
69
  ): Promise<{
64
70
  ruleset: Ruleset;
65
- compiler: { version: string; warnings: any[] };
71
+ compiler: DbUrlRuleset["compiler"];
66
72
  }> {
67
73
  const jsFile = path.resolve(
68
74
  rulesetDir,
69
- krlCompilerVersion,
75
+ compileGenerationDir(),
70
76
  hash.substr(0, 2),
71
77
  hash.substr(2, 2),
72
78
  hash + ".js"
@@ -97,15 +103,24 @@ export async function createRulesetRegistryLoaderFs(
97
103
 
98
104
  const ruleset: Ruleset = require(jsFile);
99
105
 
106
+ const compileGeneration = rulesetCompileGeneration();
100
107
  return {
101
108
  ruleset,
102
- compiler: { version: krlCompilerVersion, warnings: compileWarnings },
109
+ compiler: {
110
+ version: krlCompilerVersion,
111
+ warnings: compileWarnings,
112
+ compileGeneration,
113
+ },
103
114
  };
104
115
  }
105
116
 
106
117
  const loader: RulesetRegistryLoader = {
107
118
  fetchKrl,
108
119
 
120
+ getCompileGeneration() {
121
+ return rulesetCompileGeneration();
122
+ },
123
+
109
124
  async save({ ruleset, ...rest }) {
110
125
  let toWrite: DbUrlRuleset = rest;
111
126
  await db.put(["url", toWrite.url], toWrite);
@@ -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";
@@ -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
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,50 +51,48 @@ 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
23
57
 
24
- Environment Variables:
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.
25
61
 
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.
33
- `);
34
- process.exit(0);
35
- }
62
+ Configuration (preferred):
36
63
 
37
- const env: PicoEngineConfiguration = {};
64
+ ~/.config/pico-engine/config.json
65
+ (or --config / PICO_ENGINE_CONFIG to another file path)
38
66
 
39
- if (process.env.PORT) {
40
- const port = parseInt(process.env.PORT, 10);
41
- if (port > 0) {
42
- env.port = port;
43
- }
44
- }
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.)
45
70
 
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
- }
71
+ Environment (optional; Docker/CI when not set in config file):
52
72
 
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;
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
82
+ `);
83
+ process.exit(0);
58
84
  }
59
85
 
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;
65
- }
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
+ };
66
96
 
67
97
  function installGracefulShutdown(engine: PicoEngine) {
68
98
  let shuttingDown = false;
@@ -96,3 +126,4 @@ startEngine(env)
96
126
  console.error(err);
97
127
  process.exit(1);
98
128
  });
129
+ }
@@ -0,0 +1,345 @@
1
+ import * as fs from "fs";
2
+ import * as os from "os";
3
+ import * as path from "path";
4
+ import type {
5
+ EventPolicyRule,
6
+ PolicyCeiling,
7
+ QueryPolicyRule,
8
+ } from "pico-framework";
9
+ import {
10
+ parseGlobalEventDenyFromJson,
11
+ parseGlobalQueryDenyFromJson,
12
+ parsePolicyCeilingFromJson,
13
+ } from "./policyConfigFromJson";
14
+
15
+ const homeDir = require("home-dir") as (sub?: string) => string;
16
+
17
+ /**
18
+ * Operator settings (file + env). Ephemeral state stays under {@link home} (DB, cache, logs).
19
+ * Config file default: ~/.config/pico-engine/config.json (override with PICO_ENGINE_CONFIG).
20
+ */
21
+ export interface EngineSettings {
22
+ home: string;
23
+ port: number;
24
+ baseUrl: string;
25
+ rpID?: string;
26
+ rpName?: string;
27
+ origin?: string;
28
+ allowSelfSignup: boolean;
29
+ /** When true, localhost may call /c/* without passkey (dev MCP, ctx HTTP loops). */
30
+ allowLocalhostChannelBypass: boolean;
31
+ wildcardSkyRequireBearer: boolean;
32
+ logToStdout: boolean;
33
+ /** Absolute log file path; ignored when logToStdout is true. */
34
+ logFile?: string;
35
+ /** Max channel policy for root picos when none stored on the pico (1.8). */
36
+ defaultRootPolicyCeiling?: PolicyCeiling;
37
+ /** Deny rules applied on every ECI before per-channel policy (1.8). */
38
+ globalEventDeny?: EventPolicyRule[];
39
+ globalQueryDeny?: QueryPolicyRule[];
40
+ }
41
+
42
+ export interface EngineSettingsOverrides {
43
+ home?: string;
44
+ port?: number;
45
+ baseUrl?: string;
46
+ base_url?: string;
47
+ rpID?: string;
48
+ rpName?: string;
49
+ origin?: string;
50
+ allowSelfSignup?: boolean;
51
+ allowLocalhostChannelBypass?: boolean;
52
+ wildcardSkyRequireBearer?: boolean;
53
+ logToStdout?: boolean;
54
+ logFile?: string;
55
+ defaultRootPolicyCeiling?: PolicyCeiling;
56
+ globalEventDeny?: EventPolicyRule[];
57
+ globalQueryDeny?: QueryPolicyRule[];
58
+ }
59
+
60
+ let runtimeSettings: EngineSettings | null = null;
61
+
62
+ export function installEngineRuntimeSettings(settings: EngineSettings): void {
63
+ runtimeSettings = settings;
64
+ }
65
+
66
+ export function getEngineRuntimeSettings(): EngineSettings {
67
+ if (!runtimeSettings) {
68
+ runtimeSettings = defaultEngineSettings();
69
+ }
70
+ return runtimeSettings;
71
+ }
72
+
73
+ export function defaultEngineSettings(): EngineSettings {
74
+ return {
75
+ home: homeDir(".pico-engine") as string,
76
+ port: 3000,
77
+ baseUrl: "http://localhost:3000",
78
+ allowSelfSignup: false,
79
+ allowLocalhostChannelBypass: true,
80
+ wildcardSkyRequireBearer: false,
81
+ logToStdout: false,
82
+ };
83
+ }
84
+
85
+ export function defaultEngineConfigFilePath(): string {
86
+ const xdg =
87
+ process.env.XDG_CONFIG_HOME &&
88
+ process.env.XDG_CONFIG_HOME.trim().length > 0
89
+ ? process.env.XDG_CONFIG_HOME
90
+ : path.join(os.homedir(), ".config");
91
+ return path.join(xdg, "pico-engine", "config.json");
92
+ }
93
+
94
+ export function resolveEngineConfigFilePath(): string {
95
+ const explicit = process.env.PICO_ENGINE_CONFIG;
96
+ if (typeof explicit === "string" && explicit.trim().length > 0) {
97
+ return path.resolve(expandHome(explicit.trim()));
98
+ }
99
+ return defaultEngineConfigFilePath();
100
+ }
101
+
102
+ /**
103
+ * Parse `--config` / `-c` from argv and set `PICO_ENGINE_CONFIG` before settings resolve.
104
+ * Use one config file per engine process (host or container).
105
+ */
106
+ export function applyConfigCliArgs(argv: string[]): string[] {
107
+ const out: string[] = [];
108
+ for (let i = 0; i < argv.length; i++) {
109
+ const arg = argv[i];
110
+ if (arg === "--config" || arg === "-c") {
111
+ const val = argv[++i];
112
+ if (typeof val !== "string" || val.length === 0) {
113
+ throw new Error(`${arg} requires a config file path`);
114
+ }
115
+ process.env.PICO_ENGINE_CONFIG = path.resolve(expandHome(val));
116
+ continue;
117
+ }
118
+ if (arg.startsWith("--config=")) {
119
+ const val = arg.slice("--config=".length);
120
+ if (val.length === 0) {
121
+ throw new Error("--config= requires a config file path");
122
+ }
123
+ process.env.PICO_ENGINE_CONFIG = path.resolve(expandHome(val));
124
+ continue;
125
+ }
126
+ out.push(arg);
127
+ }
128
+ return out;
129
+ }
130
+
131
+ function expandHome(p: string): string {
132
+ if (p.startsWith("~/")) {
133
+ return path.join(os.homedir(), p.slice(2));
134
+ }
135
+ return p;
136
+ }
137
+
138
+ function parseConfigFile(raw: string): Partial<EngineSettings> {
139
+ let data: unknown;
140
+ try {
141
+ data = JSON.parse(raw);
142
+ } catch (err) {
143
+ throw new Error(
144
+ `Invalid engine config JSON (${resolveEngineConfigFilePath()}): ${err}`,
145
+ );
146
+ }
147
+ if (!data || typeof data !== "object" || Array.isArray(data)) {
148
+ throw new Error("Engine config must be a JSON object");
149
+ }
150
+ const o = data as Record<string, unknown>;
151
+ const out: Partial<EngineSettings> = {};
152
+
153
+ if (typeof o.home === "string" && o.home.length > 0) {
154
+ out.home = expandHome(o.home);
155
+ }
156
+ if (typeof o.port === "number" && o.port >= 0) {
157
+ out.port = o.port;
158
+ }
159
+ if (typeof o.baseUrl === "string" && o.baseUrl.length > 0) {
160
+ out.baseUrl = o.baseUrl;
161
+ }
162
+ const webauthn =
163
+ o.webauthn && typeof o.webauthn === "object" && !Array.isArray(o.webauthn)
164
+ ? (o.webauthn as Record<string, unknown>)
165
+ : null;
166
+ if (webauthn) {
167
+ if (typeof webauthn.rpId === "string") out.rpID = webauthn.rpId;
168
+ if (typeof webauthn.rpName === "string") out.rpName = webauthn.rpName;
169
+ if (typeof webauthn.origin === "string") out.origin = webauthn.origin;
170
+ }
171
+ if (typeof o.rpID === "string") out.rpID = o.rpID;
172
+ if (typeof o.rpName === "string") out.rpName = o.rpName;
173
+ if (typeof o.origin === "string") out.origin = o.origin;
174
+ if (typeof o.allowSelfSignup === "boolean") {
175
+ out.allowSelfSignup = o.allowSelfSignup;
176
+ }
177
+ if (typeof o.allowLocalhostChannelBypass === "boolean") {
178
+ out.allowLocalhostChannelBypass = o.allowLocalhostChannelBypass;
179
+ }
180
+ if (typeof o.wildcardSkyRequireBearer === "boolean") {
181
+ out.wildcardSkyRequireBearer = o.wildcardSkyRequireBearer;
182
+ }
183
+ if (typeof o.logToStdout === "boolean") {
184
+ out.logToStdout = o.logToStdout;
185
+ }
186
+ if (typeof o.logFile === "string" && o.logFile.length > 0) {
187
+ if (o.logFile === "stdout" || o.logFile === "-") {
188
+ out.logToStdout = true;
189
+ } else {
190
+ out.logFile = path.resolve(expandHome(o.logFile));
191
+ }
192
+ }
193
+ const rootCeiling = parsePolicyCeilingFromJson(
194
+ o.defaultRootPolicyCeiling,
195
+ "defaultRootPolicyCeiling",
196
+ );
197
+ if (rootCeiling) {
198
+ out.defaultRootPolicyCeiling = rootCeiling;
199
+ }
200
+ const globalEventDeny = parseGlobalEventDenyFromJson(o.globalEventDeny);
201
+ if (globalEventDeny) {
202
+ out.globalEventDeny = globalEventDeny;
203
+ }
204
+ const globalQueryDeny = parseGlobalQueryDenyFromJson(o.globalQueryDeny);
205
+ if (globalQueryDeny) {
206
+ out.globalQueryDeny = globalQueryDeny;
207
+ }
208
+
209
+ return out;
210
+ }
211
+
212
+ export function loadConfigFileSettings(): Partial<EngineSettings> {
213
+ if (process.env.NODE_ENV === "test" && !process.env.PICO_ENGINE_CONFIG) {
214
+ return {};
215
+ }
216
+ const filePath = resolveEngineConfigFilePath();
217
+ if (!fs.existsSync(filePath)) {
218
+ return {};
219
+ }
220
+ const raw = fs.readFileSync(filePath, "utf8");
221
+ return parseConfigFile(raw);
222
+ }
223
+
224
+ function parseBoolEnv(val: string | undefined): boolean | undefined {
225
+ if (val === undefined) return undefined;
226
+ if (val === "true" || val === "1") return true;
227
+ if (val === "false" || val === "0") return false;
228
+ return undefined;
229
+ }
230
+
231
+ export function settingsFromEnv(): Partial<EngineSettings> {
232
+ const out: Partial<EngineSettings> = {};
233
+
234
+ if (process.env.PORT) {
235
+ const port = parseInt(process.env.PORT, 10);
236
+ if (port >= 0) out.port = port;
237
+ }
238
+ if (
239
+ typeof process.env.PICO_ENGINE_HOME === "string" &&
240
+ process.env.PICO_ENGINE_HOME.length > 0
241
+ ) {
242
+ out.home = expandHome(process.env.PICO_ENGINE_HOME);
243
+ }
244
+ if (
245
+ typeof process.env.PICO_ENGINE_BASE_URL === "string" &&
246
+ process.env.PICO_ENGINE_BASE_URL.length > 0
247
+ ) {
248
+ out.baseUrl = process.env.PICO_ENGINE_BASE_URL;
249
+ }
250
+ if (
251
+ typeof process.env.PICO_ENGINE_RP_ID === "string" &&
252
+ process.env.PICO_ENGINE_RP_ID.length > 0
253
+ ) {
254
+ out.rpID = process.env.PICO_ENGINE_RP_ID;
255
+ }
256
+ if (
257
+ typeof process.env.PICO_ENGINE_ORIGIN === "string" &&
258
+ process.env.PICO_ENGINE_ORIGIN.length > 0
259
+ ) {
260
+ out.origin = process.env.PICO_ENGINE_ORIGIN;
261
+ }
262
+ const signup = parseBoolEnv(process.env.PICO_ENGINE_ALLOW_SELF_SIGNUP);
263
+ if (signup !== undefined) out.allowSelfSignup = signup;
264
+ const localhostC = parseBoolEnv(process.env.PICO_ENGINE_ALLOW_LOCALHOST_C);
265
+ if (localhostC !== undefined) {
266
+ out.allowLocalhostChannelBypass = localhostC;
267
+ } else if (process.env.PICO_ENGINE_ALLOW_LOCALHOST_C === "0") {
268
+ out.allowLocalhostChannelBypass = false;
269
+ }
270
+ const wildcard = parseBoolEnv(
271
+ process.env.PICO_ENGINE_WILDCARD_SKY_REQUIRE_BEARER,
272
+ );
273
+ if (wildcard !== undefined) out.wildcardSkyRequireBearer = wildcard;
274
+ const logFile = process.env.PICO_ENGINE_LOG_FILE;
275
+ if (logFile === "0" || logFile === "-" || logFile === "stdout" || logFile === "") {
276
+ out.logToStdout = true;
277
+ } else if (typeof logFile === "string" && logFile.length > 0) {
278
+ out.logFile = path.resolve(expandHome(logFile));
279
+ }
280
+
281
+ return out;
282
+ }
283
+
284
+ function mergeSettings(
285
+ base: EngineSettings,
286
+ ...layers: Partial<EngineSettings>[]
287
+ ): EngineSettings {
288
+ const merged = { ...base };
289
+ for (const layer of layers) {
290
+ Object.assign(merged, layer);
291
+ }
292
+ return merged;
293
+ }
294
+
295
+ /**
296
+ * Resolve settings: defaults ← environment ← config file ← programmatic (tests, API).
297
+ * `PORT` and `PICO_ENGINE_HOME` (and other env keys) apply when the file omits them;
298
+ * values in the config file win when both are set.
299
+ */
300
+ export function resolveEngineSettings(
301
+ programmatic: EngineSettingsOverrides = {},
302
+ ): EngineSettings {
303
+ const fromProgrammatic: Partial<EngineSettings> = {};
304
+ if (programmatic.home) fromProgrammatic.home = programmatic.home;
305
+ if (programmatic.port != null) fromProgrammatic.port = programmatic.port;
306
+ const baseUrl = programmatic.baseUrl ?? programmatic.base_url;
307
+ if (baseUrl) fromProgrammatic.baseUrl = baseUrl;
308
+ if (programmatic.rpID) fromProgrammatic.rpID = programmatic.rpID;
309
+ if (programmatic.rpName) fromProgrammatic.rpName = programmatic.rpName;
310
+ if (programmatic.origin) fromProgrammatic.origin = programmatic.origin;
311
+ if (programmatic.allowSelfSignup !== undefined) {
312
+ fromProgrammatic.allowSelfSignup = programmatic.allowSelfSignup;
313
+ }
314
+ if (programmatic.allowLocalhostChannelBypass !== undefined) {
315
+ fromProgrammatic.allowLocalhostChannelBypass =
316
+ programmatic.allowLocalhostChannelBypass;
317
+ }
318
+ if (programmatic.wildcardSkyRequireBearer !== undefined) {
319
+ fromProgrammatic.wildcardSkyRequireBearer =
320
+ programmatic.wildcardSkyRequireBearer;
321
+ }
322
+ if (programmatic.logToStdout !== undefined) {
323
+ fromProgrammatic.logToStdout = programmatic.logToStdout;
324
+ }
325
+ if (programmatic.logFile !== undefined) {
326
+ fromProgrammatic.logFile = programmatic.logFile;
327
+ }
328
+ if (programmatic.defaultRootPolicyCeiling !== undefined) {
329
+ fromProgrammatic.defaultRootPolicyCeiling =
330
+ programmatic.defaultRootPolicyCeiling;
331
+ }
332
+ if (programmatic.globalEventDeny !== undefined) {
333
+ fromProgrammatic.globalEventDeny = programmatic.globalEventDeny;
334
+ }
335
+ if (programmatic.globalQueryDeny !== undefined) {
336
+ fromProgrammatic.globalQueryDeny = programmatic.globalQueryDeny;
337
+ }
338
+
339
+ return mergeSettings(
340
+ defaultEngineSettings(),
341
+ settingsFromEnv(),
342
+ loadConfigFileSettings(),
343
+ fromProgrammatic,
344
+ );
345
+ }