@fideliosai/server 2026.331.0-canary.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.
- package/LICENSE +22 -0
- package/dist/adapters/codex-models.d.ts +4 -0
- package/dist/adapters/codex-models.d.ts.map +1 -0
- package/dist/adapters/codex-models.js +98 -0
- package/dist/adapters/codex-models.js.map +1 -0
- package/dist/adapters/cursor-models.d.ts +13 -0
- package/dist/adapters/cursor-models.d.ts.map +1 -0
- package/dist/adapters/cursor-models.js +148 -0
- package/dist/adapters/cursor-models.js.map +1 -0
- package/dist/adapters/http/execute.d.ts +3 -0
- package/dist/adapters/http/execute.d.ts.map +1 -0
- package/dist/adapters/http/execute.js +39 -0
- package/dist/adapters/http/execute.js.map +1 -0
- package/dist/adapters/http/index.d.ts +3 -0
- package/dist/adapters/http/index.d.ts.map +1 -0
- package/dist/adapters/http/index.js +20 -0
- package/dist/adapters/http/index.js.map +1 -0
- package/dist/adapters/http/test.d.ts +3 -0
- package/dist/adapters/http/test.d.ts.map +1 -0
- package/dist/adapters/http/test.js +106 -0
- package/dist/adapters/http/test.js.map +1 -0
- package/dist/adapters/index.d.ts +4 -0
- package/dist/adapters/index.d.ts.map +1 -0
- package/dist/adapters/index.js +3 -0
- package/dist/adapters/index.js.map +1 -0
- package/dist/adapters/process/execute.d.ts +3 -0
- package/dist/adapters/process/execute.d.ts.map +1 -0
- package/dist/adapters/process/execute.js +63 -0
- package/dist/adapters/process/execute.js.map +1 -0
- package/dist/adapters/process/index.d.ts +3 -0
- package/dist/adapters/process/index.d.ts.map +1 -0
- package/dist/adapters/process/index.js +23 -0
- package/dist/adapters/process/index.js.map +1 -0
- package/dist/adapters/process/test.d.ts +3 -0
- package/dist/adapters/process/test.d.ts.map +1 -0
- package/dist/adapters/process/test.js +77 -0
- package/dist/adapters/process/test.js.map +1 -0
- package/dist/adapters/registry.d.ts +14 -0
- package/dist/adapters/registry.d.ts.map +1 -0
- package/dist/adapters/registry.js +164 -0
- package/dist/adapters/registry.js.map +1 -0
- package/dist/adapters/types.d.ts +2 -0
- package/dist/adapters/types.d.ts.map +1 -0
- package/dist/adapters/types.js +2 -0
- package/dist/adapters/types.js.map +1 -0
- package/dist/adapters/utils.d.ts +10 -0
- package/dist/adapters/utils.d.ts.map +1 -0
- package/dist/adapters/utils.js +14 -0
- package/dist/adapters/utils.js.map +1 -0
- package/dist/agent-auth-jwt.d.ts +14 -0
- package/dist/agent-auth-jwt.d.ts.map +1 -0
- package/dist/agent-auth-jwt.js +117 -0
- package/dist/agent-auth-jwt.js.map +1 -0
- package/dist/app.d.ts +25 -0
- package/dist/app.d.ts.map +1 -0
- package/dist/app.js +265 -0
- package/dist/app.js.map +1 -0
- package/dist/attachment-types.d.ts +33 -0
- package/dist/attachment-types.d.ts.map +1 -0
- package/dist/attachment-types.js +67 -0
- package/dist/attachment-types.js.map +1 -0
- package/dist/auth/better-auth.d.ts +24 -0
- package/dist/auth/better-auth.d.ts.map +1 -0
- package/dist/auth/better-auth.js +108 -0
- package/dist/auth/better-auth.js.map +1 -0
- package/dist/board-claim.d.ts +23 -0
- package/dist/board-claim.d.ts.map +1 -0
- package/dist/board-claim.js +115 -0
- package/dist/board-claim.js.map +1 -0
- package/dist/config-file.d.ts +3 -0
- package/dist/config-file.d.ts.map +1 -0
- package/dist/config-file.js +16 -0
- package/dist/config-file.js.map +1 -0
- package/dist/config.d.ts +45 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +171 -0
- package/dist/config.js.map +1 -0
- package/dist/dev-server-status.d.ts +27 -0
- package/dist/dev-server-status.d.ts.map +1 -0
- package/dist/dev-server-status.js +70 -0
- package/dist/dev-server-status.js.map +1 -0
- package/dist/dev-watch-ignore.d.ts +2 -0
- package/dist/dev-watch-ignore.d.ts.map +1 -0
- package/dist/dev-watch-ignore.js +33 -0
- package/dist/dev-watch-ignore.js.map +1 -0
- package/dist/errors.d.ts +12 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +28 -0
- package/dist/errors.js.map +1 -0
- package/dist/home-paths.d.ts +17 -0
- package/dist/home-paths.d.ts.map +1 -0
- package/dist/home-paths.js +75 -0
- package/dist/home-paths.js.map +1 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +642 -0
- package/dist/index.js.map +1 -0
- package/dist/log-redaction.d.ts +11 -0
- package/dist/log-redaction.d.ts.map +1 -0
- package/dist/log-redaction.js +118 -0
- package/dist/log-redaction.js.map +1 -0
- package/dist/middleware/auth.d.ts +12 -0
- package/dist/middleware/auth.d.ts.map +1 -0
- package/dist/middleware/auth.js +144 -0
- package/dist/middleware/auth.js.map +1 -0
- package/dist/middleware/board-mutation-guard.d.ts +3 -0
- package/dist/middleware/board-mutation-guard.d.ts.map +1 -0
- package/dist/middleware/board-mutation-guard.js +59 -0
- package/dist/middleware/board-mutation-guard.js.map +1 -0
- package/dist/middleware/error-handler.d.ts +17 -0
- package/dist/middleware/error-handler.d.ts.map +1 -0
- package/dist/middleware/error-handler.js +37 -0
- package/dist/middleware/error-handler.js.map +1 -0
- package/dist/middleware/index.d.ts +4 -0
- package/dist/middleware/index.d.ts.map +1 -0
- package/dist/middleware/index.js +4 -0
- package/dist/middleware/index.js.map +1 -0
- package/dist/middleware/logger.d.ts +4 -0
- package/dist/middleware/logger.d.ts.map +1 -0
- package/dist/middleware/logger.js +87 -0
- package/dist/middleware/logger.js.map +1 -0
- package/dist/middleware/private-hostname-guard.d.ts +11 -0
- package/dist/middleware/private-hostname-guard.d.ts.map +1 -0
- package/dist/middleware/private-hostname-guard.js +78 -0
- package/dist/middleware/private-hostname-guard.js.map +1 -0
- package/dist/middleware/validate.d.ts +4 -0
- package/dist/middleware/validate.d.ts.map +1 -0
- package/dist/middleware/validate.js +7 -0
- package/dist/middleware/validate.js.map +1 -0
- package/dist/onboarding-assets/ceo/AGENTS.md +54 -0
- package/dist/onboarding-assets/ceo/HEARTBEAT.md +72 -0
- package/dist/onboarding-assets/ceo/SOUL.md +33 -0
- package/dist/onboarding-assets/ceo/TOOLS.md +3 -0
- package/dist/onboarding-assets/default/AGENTS.md +3 -0
- package/dist/paths.d.ts +3 -0
- package/dist/paths.d.ts.map +1 -0
- package/dist/paths.js +31 -0
- package/dist/paths.js.map +1 -0
- package/dist/realtime/live-events-ws.d.ts +28 -0
- package/dist/realtime/live-events-ws.d.ts.map +1 -0
- package/dist/realtime/live-events-ws.js +187 -0
- package/dist/realtime/live-events-ws.js.map +1 -0
- package/dist/redaction.d.ts +4 -0
- package/dist/redaction.d.ts.map +1 -0
- package/dist/redaction.js +63 -0
- package/dist/redaction.js.map +1 -0
- package/dist/routes/access.d.ts +61 -0
- package/dist/routes/access.d.ts.map +1 -0
- package/dist/routes/access.js +2265 -0
- package/dist/routes/access.js.map +1 -0
- package/dist/routes/activity.d.ts +3 -0
- package/dist/routes/activity.d.ts.map +1 -0
- package/dist/routes/activity.js +78 -0
- package/dist/routes/activity.js.map +1 -0
- package/dist/routes/agents.d.ts +3 -0
- package/dist/routes/agents.d.ts.map +1 -0
- package/dist/routes/agents.js +1828 -0
- package/dist/routes/agents.js.map +1 -0
- package/dist/routes/approvals.d.ts +3 -0
- package/dist/routes/approvals.d.ts.map +1 -0
- package/dist/routes/approvals.js +275 -0
- package/dist/routes/approvals.js.map +1 -0
- package/dist/routes/assets.d.ts +4 -0
- package/dist/routes/assets.d.ts.map +1 -0
- package/dist/routes/assets.js +309 -0
- package/dist/routes/assets.js.map +1 -0
- package/dist/routes/authz.d.ts +16 -0
- package/dist/routes/authz.d.ts.map +1 -0
- package/dist/routes/authz.js +47 -0
- package/dist/routes/authz.js.map +1 -0
- package/dist/routes/companies.d.ts +4 -0
- package/dist/routes/companies.d.ts.map +1 -0
- package/dist/routes/companies.js +303 -0
- package/dist/routes/companies.js.map +1 -0
- package/dist/routes/company-skills.d.ts +3 -0
- package/dist/routes/company-skills.d.ts.map +1 -0
- package/dist/routes/company-skills.js +228 -0
- package/dist/routes/company-skills.js.map +1 -0
- package/dist/routes/costs.d.ts +3 -0
- package/dist/routes/costs.d.ts.map +1 -0
- package/dist/routes/costs.js +268 -0
- package/dist/routes/costs.js.map +1 -0
- package/dist/routes/dashboard.d.ts +3 -0
- package/dist/routes/dashboard.d.ts.map +1 -0
- package/dist/routes/dashboard.js +15 -0
- package/dist/routes/dashboard.js.map +1 -0
- package/dist/routes/execution-workspaces.d.ts +3 -0
- package/dist/routes/execution-workspaces.d.ts.map +1 -0
- package/dist/routes/execution-workspaces.js +165 -0
- package/dist/routes/execution-workspaces.js.map +1 -0
- package/dist/routes/goals.d.ts +3 -0
- package/dist/routes/goals.d.ts.map +1 -0
- package/dist/routes/goals.js +95 -0
- package/dist/routes/goals.js.map +1 -0
- package/dist/routes/health.d.ts +9 -0
- package/dist/routes/health.d.ts.map +1 -0
- package/dist/routes/health.js +69 -0
- package/dist/routes/health.js.map +1 -0
- package/dist/routes/index.d.ts +18 -0
- package/dist/routes/index.d.ts.map +1 -0
- package/dist/routes/index.js +18 -0
- package/dist/routes/index.js.map +1 -0
- package/dist/routes/instance-settings.d.ts +3 -0
- package/dist/routes/instance-settings.d.ts.map +1 -0
- package/dist/routes/instance-settings.js +71 -0
- package/dist/routes/instance-settings.js.map +1 -0
- package/dist/routes/issues-checkout-wakeup.d.ts +9 -0
- package/dist/routes/issues-checkout-wakeup.d.ts.map +1 -0
- package/dist/routes/issues-checkout-wakeup.js +12 -0
- package/dist/routes/issues-checkout-wakeup.js.map +1 -0
- package/dist/routes/issues.d.ts +4 -0
- package/dist/routes/issues.d.ts.map +1 -0
- package/dist/routes/issues.js +1520 -0
- package/dist/routes/issues.js.map +1 -0
- package/dist/routes/llms.d.ts +3 -0
- package/dist/routes/llms.d.ts.map +1 -0
- package/dist/routes/llms.js +78 -0
- package/dist/routes/llms.js.map +1 -0
- package/dist/routes/org-chart-svg.d.ts +25 -0
- package/dist/routes/org-chart-svg.d.ts.map +1 -0
- package/dist/routes/org-chart-svg.js +657 -0
- package/dist/routes/org-chart-svg.js.map +1 -0
- package/dist/routes/plugin-ui-static.d.ts +69 -0
- package/dist/routes/plugin-ui-static.d.ts.map +1 -0
- package/dist/routes/plugin-ui-static.js +411 -0
- package/dist/routes/plugin-ui-static.js.map +1 -0
- package/dist/routes/plugins.d.ts +120 -0
- package/dist/routes/plugins.d.ts.map +1 -0
- package/dist/routes/plugins.js +1784 -0
- package/dist/routes/plugins.js.map +1 -0
- package/dist/routes/projects.d.ts +3 -0
- package/dist/routes/projects.d.ts.map +1 -0
- package/dist/routes/projects.js +257 -0
- package/dist/routes/projects.js.map +1 -0
- package/dist/routes/routines.d.ts +3 -0
- package/dist/routes/routines.d.ts.map +1 -0
- package/dist/routes/routines.js +277 -0
- package/dist/routes/routines.js.map +1 -0
- package/dist/routes/secrets.d.ts +3 -0
- package/dist/routes/secrets.d.ts.map +1 -0
- package/dist/routes/secrets.js +128 -0
- package/dist/routes/secrets.js.map +1 -0
- package/dist/routes/sidebar-badges.d.ts +3 -0
- package/dist/routes/sidebar-badges.d.ts.map +1 -0
- package/dist/routes/sidebar-badges.js +45 -0
- package/dist/routes/sidebar-badges.js.map +1 -0
- package/dist/secrets/external-stub-providers.d.ts +5 -0
- package/dist/secrets/external-stub-providers.d.ts.map +1 -0
- package/dist/secrets/external-stub-providers.js +21 -0
- package/dist/secrets/external-stub-providers.js.map +1 -0
- package/dist/secrets/local-encrypted-provider.d.ts +3 -0
- package/dist/secrets/local-encrypted-provider.d.ts.map +1 -0
- package/dist/secrets/local-encrypted-provider.js +116 -0
- package/dist/secrets/local-encrypted-provider.js.map +1 -0
- package/dist/secrets/provider-registry.d.ts +5 -0
- package/dist/secrets/provider-registry.d.ts.map +1 -0
- package/dist/secrets/provider-registry.js +20 -0
- package/dist/secrets/provider-registry.js.map +1 -0
- package/dist/secrets/types.d.ts +21 -0
- package/dist/secrets/types.d.ts.map +1 -0
- package/dist/secrets/types.js +2 -0
- package/dist/secrets/types.js.map +1 -0
- package/dist/services/access.d.ts +113 -0
- package/dist/services/access.d.ts.map +1 -0
- package/dist/services/access.js +247 -0
- package/dist/services/access.js.map +1 -0
- package/dist/services/activity-log.d.ts +17 -0
- package/dist/services/activity-log.d.ts.map +1 -0
- package/dist/services/activity-log.js +74 -0
- package/dist/services/activity-log.js.map +1 -0
- package/dist/services/activity.d.ts +764 -0
- package/dist/services/activity.d.ts.map +1 -0
- package/dist/services/activity.js +105 -0
- package/dist/services/activity.js.map +1 -0
- package/dist/services/agent-instructions.d.ts +91 -0
- package/dist/services/agent-instructions.d.ts.map +1 -0
- package/dist/services/agent-instructions.js +580 -0
- package/dist/services/agent-instructions.js.map +1 -0
- package/dist/services/agent-permissions.d.ts +6 -0
- package/dist/services/agent-permissions.d.ts.map +1 -0
- package/dist/services/agent-permissions.js +18 -0
- package/dist/services/agent-permissions.js.map +1 -0
- package/dist/services/agents.d.ts +1670 -0
- package/dist/services/agents.d.ts.map +1 -0
- package/dist/services/agents.js +566 -0
- package/dist/services/agents.js.map +1 -0
- package/dist/services/approvals.d.ts +546 -0
- package/dist/services/approvals.d.ts.map +1 -0
- package/dist/services/approvals.js +212 -0
- package/dist/services/approvals.js.map +1 -0
- package/dist/services/assets.d.ts +33 -0
- package/dist/services/assets.d.ts.map +1 -0
- package/dist/services/assets.js +17 -0
- package/dist/services/assets.js.map +1 -0
- package/dist/services/board-auth.d.ts +234 -0
- package/dist/services/board-auth.d.ts.map +1 -0
- package/dist/services/board-auth.js +295 -0
- package/dist/services/board-auth.js.map +1 -0
- package/dist/services/budgets.d.ts +38 -0
- package/dist/services/budgets.d.ts.map +1 -0
- package/dist/services/budgets.js +784 -0
- package/dist/services/budgets.js.map +1 -0
- package/dist/services/companies.d.ts +124 -0
- package/dist/services/companies.d.ts.map +1 -0
- package/dist/services/companies.js +256 -0
- package/dist/services/companies.js.map +1 -0
- package/dist/services/company-export-readme.d.ts +17 -0
- package/dist/services/company-export-readme.d.ts.map +1 -0
- package/dist/services/company-export-readme.js +148 -0
- package/dist/services/company-export-readme.js.map +1 -0
- package/dist/services/company-portability.d.ts +23 -0
- package/dist/services/company-portability.d.ts.map +1 -0
- package/dist/services/company-portability.js +3739 -0
- package/dist/services/company-portability.js.map +1 -0
- package/dist/services/company-skills.d.ts +77 -0
- package/dist/services/company-skills.d.ts.map +1 -0
- package/dist/services/company-skills.js +2042 -0
- package/dist/services/company-skills.js.map +1 -0
- package/dist/services/costs.d.ts +114 -0
- package/dist/services/costs.d.ts.map +1 -0
- package/dist/services/costs.js +294 -0
- package/dist/services/costs.js.map +1 -0
- package/dist/services/cron.d.ts +80 -0
- package/dist/services/cron.d.ts.map +1 -0
- package/dist/services/cron.js +300 -0
- package/dist/services/cron.js.map +1 -0
- package/dist/services/dashboard.d.ts +26 -0
- package/dist/services/dashboard.d.ts.map +1 -0
- package/dist/services/dashboard.js +98 -0
- package/dist/services/dashboard.js.map +1 -0
- package/dist/services/default-agent-instructions.d.ts +9 -0
- package/dist/services/default-agent-instructions.d.ts.map +1 -0
- package/dist/services/default-agent-instructions.js +20 -0
- package/dist/services/default-agent-instructions.js.map +1 -0
- package/dist/services/documents.d.ts +164 -0
- package/dist/services/documents.d.ts.map +1 -0
- package/dist/services/documents.js +382 -0
- package/dist/services/documents.js.map +1 -0
- package/dist/services/execution-workspace-policy.d.ts +21 -0
- package/dist/services/execution-workspace-policy.d.ts.map +1 -0
- package/dist/services/execution-workspace-policy.js +177 -0
- package/dist/services/execution-workspace-policy.js.map +1 -0
- package/dist/services/execution-workspaces.d.ts +19 -0
- package/dist/services/execution-workspaces.d.ts.map +1 -0
- package/dist/services/execution-workspaces.js +87 -0
- package/dist/services/execution-workspaces.js.map +1 -0
- package/dist/services/finance.d.ts +93 -0
- package/dist/services/finance.d.ts.map +1 -0
- package/dist/services/finance.js +120 -0
- package/dist/services/finance.js.map +1 -0
- package/dist/services/goals.d.ts +433 -0
- package/dist/services/goals.d.ts.map +1 -0
- package/dist/services/goals.js +54 -0
- package/dist/services/goals.js.map +1 -0
- package/dist/services/heartbeat-run-summary.d.ts +2 -0
- package/dist/services/heartbeat-run-summary.d.ts.map +1 -0
- package/dist/services/heartbeat-run-summary.js +30 -0
- package/dist/services/heartbeat-run-summary.js.map +1 -0
- package/dist/services/heartbeat.d.ts +812 -0
- package/dist/services/heartbeat.d.ts.map +1 -0
- package/dist/services/heartbeat.js +3156 -0
- package/dist/services/heartbeat.js.map +1 -0
- package/dist/services/hire-hook.d.ts +14 -0
- package/dist/services/hire-hook.d.ts.map +1 -0
- package/dist/services/hire-hook.js +85 -0
- package/dist/services/hire-hook.js.map +1 -0
- package/dist/services/index.d.ts +33 -0
- package/dist/services/index.d.ts.map +1 -0
- package/dist/services/index.js +33 -0
- package/dist/services/index.js.map +1 -0
- package/dist/services/instance-settings.d.ts +11 -0
- package/dist/services/instance-settings.d.ts.map +1 -0
- package/dist/services/instance-settings.js +116 -0
- package/dist/services/instance-settings.js.map +1 -0
- package/dist/services/issue-approvals.d.ts +56 -0
- package/dist/services/issue-approvals.d.ts.map +1 -0
- package/dist/services/issue-approvals.js +153 -0
- package/dist/services/issue-approvals.js.map +1 -0
- package/dist/services/issue-assignment-wakeup.d.ts +29 -0
- package/dist/services/issue-assignment-wakeup.d.ts.map +1 -0
- package/dist/services/issue-assignment-wakeup.js +22 -0
- package/dist/services/issue-assignment-wakeup.js.map +1 -0
- package/dist/services/issue-goal-fallback.d.ts +18 -0
- package/dist/services/issue-goal-fallback.d.ts.map +1 -0
- package/dist/services/issue-goal-fallback.js +33 -0
- package/dist/services/issue-goal-fallback.js.map +1 -0
- package/dist/services/issues.d.ts +560 -0
- package/dist/services/issues.d.ts.map +1 -0
- package/dist/services/issues.js +1478 -0
- package/dist/services/issues.js.map +1 -0
- package/dist/services/live-events.d.ts +17 -0
- package/dist/services/live-events.d.ts.map +1 -0
- package/dist/services/live-events.js +33 -0
- package/dist/services/live-events.js.map +1 -0
- package/dist/services/plugin-capability-validator.d.ts +108 -0
- package/dist/services/plugin-capability-validator.d.ts.map +1 -0
- package/dist/services/plugin-capability-validator.js +268 -0
- package/dist/services/plugin-capability-validator.js.map +1 -0
- package/dist/services/plugin-config-validator.d.ts +26 -0
- package/dist/services/plugin-config-validator.d.ts.map +1 -0
- package/dist/services/plugin-config-validator.js +41 -0
- package/dist/services/plugin-config-validator.js.map +1 -0
- package/dist/services/plugin-dev-watcher.d.ts +30 -0
- package/dist/services/plugin-dev-watcher.d.ts.map +1 -0
- package/dist/services/plugin-dev-watcher.js +241 -0
- package/dist/services/plugin-dev-watcher.js.map +1 -0
- package/dist/services/plugin-event-bus.d.ts +149 -0
- package/dist/services/plugin-event-bus.d.ts.map +1 -0
- package/dist/services/plugin-event-bus.js +258 -0
- package/dist/services/plugin-event-bus.js.map +1 -0
- package/dist/services/plugin-host-service-cleanup.d.ts +14 -0
- package/dist/services/plugin-host-service-cleanup.d.ts.map +1 -0
- package/dist/services/plugin-host-service-cleanup.js +37 -0
- package/dist/services/plugin-host-service-cleanup.js.map +1 -0
- package/dist/services/plugin-host-services.d.ts +13 -0
- package/dist/services/plugin-host-services.d.ts.map +1 -0
- package/dist/services/plugin-host-services.js +969 -0
- package/dist/services/plugin-host-services.js.map +1 -0
- package/dist/services/plugin-job-coordinator.d.ts +81 -0
- package/dist/services/plugin-job-coordinator.d.ts.map +1 -0
- package/dist/services/plugin-job-coordinator.js +172 -0
- package/dist/services/plugin-job-coordinator.js.map +1 -0
- package/dist/services/plugin-job-scheduler.d.ts +163 -0
- package/dist/services/plugin-job-scheduler.d.ts.map +1 -0
- package/dist/services/plugin-job-scheduler.js +454 -0
- package/dist/services/plugin-job-scheduler.js.map +1 -0
- package/dist/services/plugin-job-store.d.ts +208 -0
- package/dist/services/plugin-job-store.d.ts.map +1 -0
- package/dist/services/plugin-job-store.js +350 -0
- package/dist/services/plugin-job-store.js.map +1 -0
- package/dist/services/plugin-lifecycle.d.ts +203 -0
- package/dist/services/plugin-lifecycle.d.ts.map +1 -0
- package/dist/services/plugin-lifecycle.js +476 -0
- package/dist/services/plugin-lifecycle.js.map +1 -0
- package/dist/services/plugin-loader.d.ts +441 -0
- package/dist/services/plugin-loader.d.ts.map +1 -0
- package/dist/services/plugin-loader.js +1192 -0
- package/dist/services/plugin-loader.js.map +1 -0
- package/dist/services/plugin-log-retention.d.ts +20 -0
- package/dist/services/plugin-log-retention.d.ts.map +1 -0
- package/dist/services/plugin-log-retention.js +63 -0
- package/dist/services/plugin-log-retention.js.map +1 -0
- package/dist/services/plugin-manifest-validator.d.ts +79 -0
- package/dist/services/plugin-manifest-validator.d.ts.map +1 -0
- package/dist/services/plugin-manifest-validator.js +84 -0
- package/dist/services/plugin-manifest-validator.js.map +1 -0
- package/dist/services/plugin-registry.d.ts +2542 -0
- package/dist/services/plugin-registry.d.ts.map +1 -0
- package/dist/services/plugin-registry.js +539 -0
- package/dist/services/plugin-registry.js.map +1 -0
- package/dist/services/plugin-runtime-sandbox.d.ts +40 -0
- package/dist/services/plugin-runtime-sandbox.d.ts.map +1 -0
- package/dist/services/plugin-runtime-sandbox.js +154 -0
- package/dist/services/plugin-runtime-sandbox.js.map +1 -0
- package/dist/services/plugin-secrets-handler.d.ts +81 -0
- package/dist/services/plugin-secrets-handler.d.ts.map +1 -0
- package/dist/services/plugin-secrets-handler.js +275 -0
- package/dist/services/plugin-secrets-handler.js.map +1 -0
- package/dist/services/plugin-state-store.d.ts +92 -0
- package/dist/services/plugin-state-store.d.ts.map +1 -0
- package/dist/services/plugin-state-store.js +190 -0
- package/dist/services/plugin-state-store.js.map +1 -0
- package/dist/services/plugin-stream-bus.d.ts +29 -0
- package/dist/services/plugin-stream-bus.d.ts.map +1 -0
- package/dist/services/plugin-stream-bus.js +48 -0
- package/dist/services/plugin-stream-bus.js.map +1 -0
- package/dist/services/plugin-tool-dispatcher.d.ts +180 -0
- package/dist/services/plugin-tool-dispatcher.d.ts.map +1 -0
- package/dist/services/plugin-tool-dispatcher.js +224 -0
- package/dist/services/plugin-tool-dispatcher.js.map +1 -0
- package/dist/services/plugin-tool-registry.d.ts +192 -0
- package/dist/services/plugin-tool-registry.d.ts.map +1 -0
- package/dist/services/plugin-tool-registry.js +224 -0
- package/dist/services/plugin-tool-registry.js.map +1 -0
- package/dist/services/plugin-worker-manager.d.ts +260 -0
- package/dist/services/plugin-worker-manager.d.ts.map +1 -0
- package/dist/services/plugin-worker-manager.js +835 -0
- package/dist/services/plugin-worker-manager.js.map +1 -0
- package/dist/services/projects.d.ts +87 -0
- package/dist/services/projects.d.ts.map +1 -0
- package/dist/services/projects.js +656 -0
- package/dist/services/projects.js.map +1 -0
- package/dist/services/quota-windows.d.ts +9 -0
- package/dist/services/quota-windows.d.ts.map +1 -0
- package/dist/services/quota-windows.js +56 -0
- package/dist/services/quota-windows.js.map +1 -0
- package/dist/services/routines.d.ts +135 -0
- package/dist/services/routines.d.ts.map +1 -0
- package/dist/services/routines.js +1105 -0
- package/dist/services/routines.js.map +1 -0
- package/dist/services/run-log-store.d.ts +34 -0
- package/dist/services/run-log-store.d.ts.map +1 -0
- package/dist/services/run-log-store.js +109 -0
- package/dist/services/run-log-store.js.map +1 -0
- package/dist/services/secrets.d.ts +511 -0
- package/dist/services/secrets.d.ts.map +1 -0
- package/dist/services/secrets.js +289 -0
- package/dist/services/secrets.js.map +1 -0
- package/dist/services/sidebar-badges.d.ts +9 -0
- package/dist/services/sidebar-badges.d.ts.map +1 -0
- package/dist/services/sidebar-badges.js +33 -0
- package/dist/services/sidebar-badges.js.map +1 -0
- package/dist/services/work-products.d.ts +14 -0
- package/dist/services/work-products.d.ts.map +1 -0
- package/dist/services/work-products.js +100 -0
- package/dist/services/work-products.js.map +1 -0
- package/dist/services/workspace-operation-log-store.d.ts +33 -0
- package/dist/services/workspace-operation-log-store.d.ts.map +1 -0
- package/dist/services/workspace-operation-log-store.js +110 -0
- package/dist/services/workspace-operation-log-store.js.map +1 -0
- package/dist/services/workspace-operations.d.ts +44 -0
- package/dist/services/workspace-operations.d.ts.map +1 -0
- package/dist/services/workspace-operations.js +211 -0
- package/dist/services/workspace-operations.js.map +1 -0
- package/dist/services/workspace-runtime.d.ts +164 -0
- package/dist/services/workspace-runtime.d.ts.map +1 -0
- package/dist/services/workspace-runtime.js +1235 -0
- package/dist/services/workspace-runtime.js.map +1 -0
- package/dist/startup-banner.d.ts +31 -0
- package/dist/startup-banner.d.ts.map +1 -0
- package/dist/startup-banner.js +117 -0
- package/dist/startup-banner.js.map +1 -0
- package/dist/storage/index.d.ts +6 -0
- package/dist/storage/index.d.ts.map +1 -0
- package/dist/storage/index.js +29 -0
- package/dist/storage/index.js.map +1 -0
- package/dist/storage/local-disk-provider.d.ts +3 -0
- package/dist/storage/local-disk-provider.d.ts.map +1 -0
- package/dist/storage/local-disk-provider.js +79 -0
- package/dist/storage/local-disk-provider.js.map +1 -0
- package/dist/storage/provider-registry.d.ts +4 -0
- package/dist/storage/provider-registry.d.ts.map +1 -0
- package/dist/storage/provider-registry.js +15 -0
- package/dist/storage/provider-registry.js.map +1 -0
- package/dist/storage/s3-provider.d.ts +11 -0
- package/dist/storage/s3-provider.d.ts.map +1 -0
- package/dist/storage/s3-provider.js +123 -0
- package/dist/storage/s3-provider.js.map +1 -0
- package/dist/storage/service.d.ts +3 -0
- package/dist/storage/service.d.ts.map +1 -0
- package/dist/storage/service.js +120 -0
- package/dist/storage/service.js.map +1 -0
- package/dist/storage/types.d.ts +55 -0
- package/dist/storage/types.d.ts.map +1 -0
- package/dist/storage/types.js +2 -0
- package/dist/storage/types.js.map +1 -0
- package/dist/ui-branding.d.ts +13 -0
- package/dist/ui-branding.d.ts.map +1 -0
- package/dist/ui-branding.js +188 -0
- package/dist/ui-branding.js.map +1 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.d.ts.map +1 -0
- package/dist/version.js +5 -0
- package/dist/version.js.map +1 -0
- package/dist/worktree-config.d.ts +19 -0
- package/dist/worktree-config.d.ts.map +1 -0
- package/dist/worktree-config.js +365 -0
- package/dist/worktree-config.js.map +1 -0
- package/package.json +90 -0
- package/skills/fidelios/SKILL.md +365 -0
- package/skills/fidelios/references/api-reference.md +647 -0
- package/skills/fidelios/references/company-skills.md +193 -0
- package/skills/fidelios-create-agent/SKILL.md +142 -0
- package/skills/fidelios-create-agent/references/api-reference.md +105 -0
- package/skills/fidelios-create-plugin/SKILL.md +101 -0
- package/skills/para-memory-files/SKILL.md +104 -0
- package/skills/para-memory-files/references/schemas.md +35 -0
- package/ui-dist/android-chrome-192x192.png +0 -0
- package/ui-dist/android-chrome-512x512.png +0 -0
- package/ui-dist/apple-touch-icon.png +0 -0
- package/ui-dist/assets/_basePickBy-DDS8rFE9.js +1 -0
- package/ui-dist/assets/_baseUniq-BTIdqnfJ.js +1 -0
- package/ui-dist/assets/apl-B4CMkyY2.js +1 -0
- package/ui-dist/assets/arc-CER6ytAf.js +1 -0
- package/ui-dist/assets/architectureDiagram-VXUJARFQ-CrJvVSPh.js +36 -0
- package/ui-dist/assets/asciiarmor-Df11BRmG.js +1 -0
- package/ui-dist/assets/asn1-EdZsLKOL.js +1 -0
- package/ui-dist/assets/asterisk-B-8jnY81.js +1 -0
- package/ui-dist/assets/blockDiagram-VD42YOAC-p-DB7nkA.js +122 -0
- package/ui-dist/assets/brainfuck-C4LP7Hcl.js +1 -0
- package/ui-dist/assets/c4Diagram-YG6GDRKO-D1K75fYz.js +10 -0
- package/ui-dist/assets/channel-B1viE-VZ.js +1 -0
- package/ui-dist/assets/chunk-4BX2VUAB-C1J-fCaK.js +1 -0
- package/ui-dist/assets/chunk-55IACEB6-CjEOgVYA.js +1 -0
- package/ui-dist/assets/chunk-B4BG7PRW-CGZwFaze.js +165 -0
- package/ui-dist/assets/chunk-DI55MBZ5-Dp2ZahPN.js +220 -0
- package/ui-dist/assets/chunk-FMBD7UC4-nXC1OkzD.js +15 -0
- package/ui-dist/assets/chunk-QN33PNHL-D_uFCkMK.js +1 -0
- package/ui-dist/assets/chunk-QZHKN3VN-CG3WK_AN.js +1 -0
- package/ui-dist/assets/chunk-TZMSLE5B-COlBSWdP.js +1 -0
- package/ui-dist/assets/classDiagram-2ON5EDUG-Cs4NEMXI.js +1 -0
- package/ui-dist/assets/classDiagram-v2-WZHVMYZB-Cs4NEMXI.js +1 -0
- package/ui-dist/assets/clike-B9uivgTg.js +1 -0
- package/ui-dist/assets/clojure-BMjYHr_A.js +1 -0
- package/ui-dist/assets/clone-CGwZV8ud.js +1 -0
- package/ui-dist/assets/cmake-BQqOBYOt.js +1 -0
- package/ui-dist/assets/cobol-CWcv1MsR.js +1 -0
- package/ui-dist/assets/coffeescript-S37ZYGWr.js +1 -0
- package/ui-dist/assets/commonlisp-DBKNyK5s.js +1 -0
- package/ui-dist/assets/cose-bilkent-S5V4N54A-B9XYqCMb.js +1 -0
- package/ui-dist/assets/crystal-SjHAIU92.js +1 -0
- package/ui-dist/assets/css-BnMrqG3P.js +1 -0
- package/ui-dist/assets/cypher-C_CwsFkJ.js +1 -0
- package/ui-dist/assets/cytoscape.esm-BQaXIfA_.js +331 -0
- package/ui-dist/assets/d-pRatUO7H.js +1 -0
- package/ui-dist/assets/dagre-6UL2VRFP-DcCdBLC7.js +4 -0
- package/ui-dist/assets/defaultLocale-DX6XiGOO.js +1 -0
- package/ui-dist/assets/diagram-PSM6KHXK-np1kLquy.js +24 -0
- package/ui-dist/assets/diagram-QEK2KX5R-C-b4qIN1.js +43 -0
- package/ui-dist/assets/diagram-S2PKOQOG-Ba-173Ug.js +24 -0
- package/ui-dist/assets/diff-DbItnlRl.js +1 -0
- package/ui-dist/assets/dockerfile-BKs6k2Af.js +1 -0
- package/ui-dist/assets/dtd-DF_7sFjM.js +1 -0
- package/ui-dist/assets/dylan-DwRh75JA.js +1 -0
- package/ui-dist/assets/ebnf-CDyGwa7X.js +1 -0
- package/ui-dist/assets/ecl-Cabwm37j.js +1 -0
- package/ui-dist/assets/eiffel-CnydiIhH.js +1 -0
- package/ui-dist/assets/elm-vLlmbW-K.js +1 -0
- package/ui-dist/assets/erDiagram-Q2GNP2WA-BBmkHiJP.js +60 -0
- package/ui-dist/assets/erlang-BNw1qcRV.js +1 -0
- package/ui-dist/assets/factor-kuTfRLto.js +1 -0
- package/ui-dist/assets/fcl-Kvtd6kyn.js +1 -0
- package/ui-dist/assets/flowDiagram-NV44I4VS-Dj_iTDkp.js +162 -0
- package/ui-dist/assets/forth-Ffai-XNe.js +1 -0
- package/ui-dist/assets/fortran-DYz_wnZ1.js +1 -0
- package/ui-dist/assets/ganttDiagram-JELNMOA3-Bn1hanTg.js +267 -0
- package/ui-dist/assets/gas-Bneqetm1.js +1 -0
- package/ui-dist/assets/gherkin-heZmZLOM.js +1 -0
- package/ui-dist/assets/gitGraphDiagram-V2S2FVAM-BjmRpty0.js +65 -0
- package/ui-dist/assets/graph-CWBOAGTW.js +1 -0
- package/ui-dist/assets/groovy-D9Dt4D0W.js +1 -0
- package/ui-dist/assets/haskell-Cw1EW3IL.js +1 -0
- package/ui-dist/assets/haxe-H-WmDvRZ.js +1 -0
- package/ui-dist/assets/http-DBlCnlav.js +1 -0
- package/ui-dist/assets/idl-BEugSyMb.js +1 -0
- package/ui-dist/assets/index-B52MtqBm.js +1 -0
- package/ui-dist/assets/index-BEBYIFOJ.js +1 -0
- package/ui-dist/assets/index-BIvl9YFB.js +1 -0
- package/ui-dist/assets/index-BNyP1gwD.js +1 -0
- package/ui-dist/assets/index-BRW6bV_B.js +6 -0
- package/ui-dist/assets/index-BcQTWaKH.js +1 -0
- package/ui-dist/assets/index-BfKYbH5T.js +13 -0
- package/ui-dist/assets/index-BhX49pA0.js +1 -0
- package/ui-dist/assets/index-BoFaTgOC.js +2 -0
- package/ui-dist/assets/index-C-Es83iE.js +7 -0
- package/ui-dist/assets/index-C3LG8kvr.js +1 -0
- package/ui-dist/assets/index-C5Z9j0rD.js +1 -0
- package/ui-dist/assets/index-CFlEF-gp.js +1 -0
- package/ui-dist/assets/index-Cjm12V39.js +1 -0
- package/ui-dist/assets/index-Cp84QmJD.css +1 -0
- package/ui-dist/assets/index-D2t01AH0.js +1 -0
- package/ui-dist/assets/index-DEt1jkxJ.js +1 -0
- package/ui-dist/assets/index-DeAKBJuz.js +3 -0
- package/ui-dist/assets/index-Du65R_Zq.js +1 -0
- package/ui-dist/assets/index-WUHteAuP.js +1 -0
- package/ui-dist/assets/index-Y_jO6IK_.js +1180 -0
- package/ui-dist/assets/index-ZQU9QA5y.js +1 -0
- package/ui-dist/assets/index-f6wRGThx.js +1 -0
- package/ui-dist/assets/index-hMuLlvYa.js +1 -0
- package/ui-dist/assets/infoDiagram-HS3SLOUP-CVMKJlmV.js +2 -0
- package/ui-dist/assets/init-Gi6I4Gst.js +1 -0
- package/ui-dist/assets/javascript-iXu5QeM3.js +1 -0
- package/ui-dist/assets/journeyDiagram-XKPGCS4Q-FrNTHHMi.js +139 -0
- package/ui-dist/assets/julia-DuME0IfC.js +1 -0
- package/ui-dist/assets/kanban-definition-3W4ZIXB7-BQYKwdVh.js +89 -0
- package/ui-dist/assets/katex-O9d3_IXG.js +261 -0
- package/ui-dist/assets/layout-BxccZ6zb.js +1 -0
- package/ui-dist/assets/linear-Db-Yv5jO.js +1 -0
- package/ui-dist/assets/livescript-BwQOo05w.js +1 -0
- package/ui-dist/assets/lua-BgMRiT3U.js +1 -0
- package/ui-dist/assets/mathematica-DTrFuWx2.js +1 -0
- package/ui-dist/assets/mbox-CNhZ1qSd.js +1 -0
- package/ui-dist/assets/mermaid.core-BCE9tDOe.js +256 -0
- package/ui-dist/assets/mindmap-definition-VGOIOE7T-ZWLuqirD.js +68 -0
- package/ui-dist/assets/mirc-CjQqDB4T.js +1 -0
- package/ui-dist/assets/mllike-CXdrOF99.js +1 -0
- package/ui-dist/assets/modelica-Dc1JOy9r.js +1 -0
- package/ui-dist/assets/mscgen-BA5vi2Kp.js +1 -0
- package/ui-dist/assets/mumps-BT43cFF4.js +1 -0
- package/ui-dist/assets/nginx-DdIZxoE0.js +1 -0
- package/ui-dist/assets/nsis-LdVXkNf5.js +1 -0
- package/ui-dist/assets/ntriples-BfvgReVJ.js +1 -0
- package/ui-dist/assets/octave-Ck1zUtKM.js +1 -0
- package/ui-dist/assets/ordinal-Cboi1Yqb.js +1 -0
- package/ui-dist/assets/oz-BzwKVEFT.js +1 -0
- package/ui-dist/assets/pascal--L3eBynH.js +1 -0
- package/ui-dist/assets/perl-CdXCOZ3F.js +1 -0
- package/ui-dist/assets/pieDiagram-ADFJNKIX-D01HRHJF.js +30 -0
- package/ui-dist/assets/pig-CevX1Tat.js +1 -0
- package/ui-dist/assets/powershell-CFHJl5sT.js +1 -0
- package/ui-dist/assets/properties-C78fOPTZ.js +1 -0
- package/ui-dist/assets/protobuf-ChK-085T.js +1 -0
- package/ui-dist/assets/pug-DeIclll2.js +1 -0
- package/ui-dist/assets/puppet-DMA9R1ak.js +1 -0
- package/ui-dist/assets/python-BuPzkPfP.js +1 -0
- package/ui-dist/assets/q-pXgVlZs6.js +1 -0
- package/ui-dist/assets/quadrantDiagram-AYHSOK5B-lAmOPnB4.js +7 -0
- package/ui-dist/assets/r-B6wPVr8A.js +1 -0
- package/ui-dist/assets/requirementDiagram-UZGBJVZJ-ByNWbh-O.js +64 -0
- package/ui-dist/assets/rpm-CTu-6PCP.js +1 -0
- package/ui-dist/assets/ruby-B2Rjki9n.js +1 -0
- package/ui-dist/assets/sankeyDiagram-TZEHDZUN-Cf_Gq84u.js +10 -0
- package/ui-dist/assets/sas-B4kiWyti.js +1 -0
- package/ui-dist/assets/scheme-C41bIUwD.js +1 -0
- package/ui-dist/assets/sequenceDiagram-WL72ISMW-Bx2VZbdr.js +145 -0
- package/ui-dist/assets/shell-CjFT_Tl9.js +1 -0
- package/ui-dist/assets/sieve-C3Gn_uJK.js +1 -0
- package/ui-dist/assets/simple-mode-GW_nhZxv.js +1 -0
- package/ui-dist/assets/smalltalk-CnHTOXQT.js +1 -0
- package/ui-dist/assets/solr-DehyRSwq.js +1 -0
- package/ui-dist/assets/sparql-DkYu6x3z.js +1 -0
- package/ui-dist/assets/spreadsheet-BCZA_wO0.js +1 -0
- package/ui-dist/assets/sql-D0XecflT.js +1 -0
- package/ui-dist/assets/stateDiagram-FKZM4ZOC-vP7G7A65.js +1 -0
- package/ui-dist/assets/stateDiagram-v2-4FDKWEC3-C2xpsAAO.js +1 -0
- package/ui-dist/assets/stex-C3f8Ysf7.js +1 -0
- package/ui-dist/assets/stylus-B533Al4x.js +1 -0
- package/ui-dist/assets/swift-BzpIVaGY.js +1 -0
- package/ui-dist/assets/tcl-DVfN8rqt.js +1 -0
- package/ui-dist/assets/textile-CnDTJFAw.js +1 -0
- package/ui-dist/assets/tiddlywiki-DO-Gjzrf.js +1 -0
- package/ui-dist/assets/tiki-DGYXhP31.js +1 -0
- package/ui-dist/assets/timeline-definition-IT6M3QCI-BJww-sEp.js +61 -0
- package/ui-dist/assets/toml-Bm5Em-hy.js +1 -0
- package/ui-dist/assets/treemap-GDKQZRPO-DUux14NY.js +162 -0
- package/ui-dist/assets/troff-wAsdV37c.js +1 -0
- package/ui-dist/assets/ttcn-CfJYG6tj.js +1 -0
- package/ui-dist/assets/ttcn-cfg-B9xdYoR4.js +1 -0
- package/ui-dist/assets/turtle-B1tBg_DP.js +1 -0
- package/ui-dist/assets/vb-CmGdzxic.js +1 -0
- package/ui-dist/assets/vbscript-BuJXcnF6.js +1 -0
- package/ui-dist/assets/velocity-D8B20fx6.js +1 -0
- package/ui-dist/assets/verilog-C6RDOZhf.js +1 -0
- package/ui-dist/assets/vhdl-lSbBsy5d.js +1 -0
- package/ui-dist/assets/webidl-ZXfAyPTL.js +1 -0
- package/ui-dist/assets/xquery-DzFWVndE.js +1 -0
- package/ui-dist/assets/xychartDiagram-PRI3JC2R-AU5ZOwAw.js +7 -0
- package/ui-dist/assets/yacas-BJ4BC0dw.js +1 -0
- package/ui-dist/assets/z80-Hz9HOZM7.js +1 -0
- package/ui-dist/brands/opencode-logo-dark-square.svg +18 -0
- package/ui-dist/brands/opencode-logo-light-square.svg +18 -0
- package/ui-dist/favicon-16x16.png +0 -0
- package/ui-dist/favicon-32x32.png +0 -0
- package/ui-dist/favicon-96x96.png +0 -0
- package/ui-dist/favicon.ico +0 -0
- package/ui-dist/favicon.svg +3 -0
- package/ui-dist/index.html +48 -0
- package/ui-dist/site.webmanifest +21 -0
- package/ui-dist/sw.js +42 -0
- package/ui-dist/worktree-favicon-16x16.png +0 -0
- package/ui-dist/worktree-favicon-32x32.png +0 -0
- package/ui-dist/worktree-favicon.ico +0 -0
- package/ui-dist/worktree-favicon.svg +3 -0
|
@@ -0,0 +1,2265 @@
|
|
|
1
|
+
import { createHash, generateKeyPairSync, randomBytes, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { Router } from "express";
|
|
6
|
+
import { and, eq, isNull, desc } from "drizzle-orm";
|
|
7
|
+
import { agentApiKeys, authUsers, invites, joinRequests } from "@fideliosai/db";
|
|
8
|
+
import { acceptInviteSchema, createCliAuthChallengeSchema, claimJoinRequestApiKeySchema, createCompanyInviteSchema, createOpenClawInvitePromptSchema, listJoinRequestsQuerySchema, resolveCliAuthChallengeSchema, updateMemberPermissionsSchema, updateUserCompanyAccessSchema, PERMISSION_KEYS } from "@fideliosai/shared";
|
|
9
|
+
import { forbidden, conflict, notFound, unauthorized, badRequest } from "../errors.js";
|
|
10
|
+
import { logger } from "../middleware/logger.js";
|
|
11
|
+
import { validate } from "../middleware/validate.js";
|
|
12
|
+
import { accessService, agentService, boardAuthService, deduplicateAgentName, logActivity, notifyHireApproved } from "../services/index.js";
|
|
13
|
+
import { assertCompanyAccess } from "./authz.js";
|
|
14
|
+
import { claimBoardOwnership, inspectBoardClaimChallenge } from "../board-claim.js";
|
|
15
|
+
function hashToken(token) {
|
|
16
|
+
return createHash("sha256").update(token).digest("hex");
|
|
17
|
+
}
|
|
18
|
+
const INVITE_TOKEN_PREFIX = "pcp_invite_";
|
|
19
|
+
const INVITE_TOKEN_ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789";
|
|
20
|
+
const INVITE_TOKEN_SUFFIX_LENGTH = 8;
|
|
21
|
+
const INVITE_TOKEN_MAX_RETRIES = 5;
|
|
22
|
+
const COMPANY_INVITE_TTL_MS = 10 * 60 * 1000;
|
|
23
|
+
function createInviteToken() {
|
|
24
|
+
const bytes = randomBytes(INVITE_TOKEN_SUFFIX_LENGTH);
|
|
25
|
+
let suffix = "";
|
|
26
|
+
for (let idx = 0; idx < INVITE_TOKEN_SUFFIX_LENGTH; idx += 1) {
|
|
27
|
+
suffix += INVITE_TOKEN_ALPHABET[bytes[idx] % INVITE_TOKEN_ALPHABET.length];
|
|
28
|
+
}
|
|
29
|
+
return `${INVITE_TOKEN_PREFIX}${suffix}`;
|
|
30
|
+
}
|
|
31
|
+
function createClaimSecret() {
|
|
32
|
+
return `pcp_claim_${randomBytes(24).toString("hex")}`;
|
|
33
|
+
}
|
|
34
|
+
export function companyInviteExpiresAt(nowMs = Date.now()) {
|
|
35
|
+
return new Date(nowMs + COMPANY_INVITE_TTL_MS);
|
|
36
|
+
}
|
|
37
|
+
function tokenHashesMatch(left, right) {
|
|
38
|
+
const leftBytes = Buffer.from(left, "utf8");
|
|
39
|
+
const rightBytes = Buffer.from(right, "utf8");
|
|
40
|
+
return (leftBytes.length === rightBytes.length &&
|
|
41
|
+
timingSafeEqual(leftBytes, rightBytes));
|
|
42
|
+
}
|
|
43
|
+
function requestBaseUrl(req) {
|
|
44
|
+
const forwardedProto = req.header("x-forwarded-proto");
|
|
45
|
+
const proto = forwardedProto?.split(",")[0]?.trim() || req.protocol || "http";
|
|
46
|
+
const host = req.header("x-forwarded-host")?.split(",")[0]?.trim() || req.header("host");
|
|
47
|
+
if (!host)
|
|
48
|
+
return "";
|
|
49
|
+
return `${proto}://${host}`;
|
|
50
|
+
}
|
|
51
|
+
function buildCliAuthApprovalPath(challengeId, token) {
|
|
52
|
+
return `/cli-auth/${challengeId}?token=${encodeURIComponent(token)}`;
|
|
53
|
+
}
|
|
54
|
+
function readSkillMarkdown(skillName) {
|
|
55
|
+
const normalized = skillName.trim().toLowerCase();
|
|
56
|
+
if (normalized !== "fidelios" &&
|
|
57
|
+
normalized !== "fidelios-create-agent" &&
|
|
58
|
+
normalized !== "fidelios-create-plugin" &&
|
|
59
|
+
normalized !== "para-memory-files")
|
|
60
|
+
return null;
|
|
61
|
+
const moduleDir = path.dirname(fileURLToPath(import.meta.url));
|
|
62
|
+
const candidates = [
|
|
63
|
+
path.resolve(moduleDir, "../../skills", normalized, "SKILL.md"), // published: dist/routes/ -> <pkg>/skills/
|
|
64
|
+
path.resolve(process.cwd(), "skills", normalized, "SKILL.md"), // cwd (e.g. monorepo root)
|
|
65
|
+
path.resolve(moduleDir, "../../../skills", normalized, "SKILL.md") // dev: src/routes/ -> repo root/skills/
|
|
66
|
+
];
|
|
67
|
+
for (const skillPath of candidates) {
|
|
68
|
+
try {
|
|
69
|
+
return fs.readFileSync(skillPath, "utf8");
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
// Continue to next candidate.
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
/** Resolve the FideliOS repo skills directory (built-in / managed skills). */
|
|
78
|
+
function resolveFideliOSSkillsDir() {
|
|
79
|
+
const moduleDir = path.dirname(fileURLToPath(import.meta.url));
|
|
80
|
+
const candidates = [
|
|
81
|
+
path.resolve(moduleDir, "../../skills"), // published
|
|
82
|
+
path.resolve(process.cwd(), "skills"), // cwd (monorepo root)
|
|
83
|
+
path.resolve(moduleDir, "../../../skills"), // dev
|
|
84
|
+
];
|
|
85
|
+
for (const candidate of candidates) {
|
|
86
|
+
try {
|
|
87
|
+
if (fs.statSync(candidate).isDirectory())
|
|
88
|
+
return candidate;
|
|
89
|
+
}
|
|
90
|
+
catch { /* skip */ }
|
|
91
|
+
}
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
/** Parse YAML frontmatter from a SKILL.md file to extract the description. */
|
|
95
|
+
function parseSkillFrontmatter(markdown) {
|
|
96
|
+
const match = markdown.match(/^---\n([\s\S]*?)\n---/);
|
|
97
|
+
if (!match)
|
|
98
|
+
return { description: "" };
|
|
99
|
+
const yaml = match[1];
|
|
100
|
+
// Extract description — handles both single-line and multi-line YAML values
|
|
101
|
+
const descMatch = yaml.match(/^description:\s*(?:>\s*\n((?:\s{2,}[^\n]*\n?)+)|[|]\s*\n((?:\s{2,}[^\n]*\n?)+)|["']?(.*?)["']?\s*$)/m);
|
|
102
|
+
if (!descMatch)
|
|
103
|
+
return { description: "" };
|
|
104
|
+
const raw = descMatch[1] ?? descMatch[2] ?? descMatch[3] ?? "";
|
|
105
|
+
return {
|
|
106
|
+
description: raw
|
|
107
|
+
.split("\n")
|
|
108
|
+
.map((l) => l.trim())
|
|
109
|
+
.filter(Boolean)
|
|
110
|
+
.join(" ")
|
|
111
|
+
.trim(),
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
/** Discover all available Claude Code skills from ~/.claude/skills/. */
|
|
115
|
+
function listAvailableSkills() {
|
|
116
|
+
const homeDir = process.env.HOME || process.env.USERPROFILE || "";
|
|
117
|
+
const claudeSkillsDir = path.join(homeDir, ".claude", "skills");
|
|
118
|
+
const fideliosSkillsDir = resolveFideliOSSkillsDir();
|
|
119
|
+
// Build set of FideliOS-managed skill names
|
|
120
|
+
const fideliosSkillNames = new Set();
|
|
121
|
+
if (fideliosSkillsDir) {
|
|
122
|
+
try {
|
|
123
|
+
for (const entry of fs.readdirSync(fideliosSkillsDir, { withFileTypes: true })) {
|
|
124
|
+
if (entry.isDirectory())
|
|
125
|
+
fideliosSkillNames.add(entry.name);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
catch { /* skip */ }
|
|
129
|
+
}
|
|
130
|
+
const skills = [];
|
|
131
|
+
try {
|
|
132
|
+
const entries = fs.readdirSync(claudeSkillsDir, { withFileTypes: true });
|
|
133
|
+
for (const entry of entries) {
|
|
134
|
+
if (!entry.isDirectory() && !entry.isSymbolicLink())
|
|
135
|
+
continue;
|
|
136
|
+
if (entry.name.startsWith("."))
|
|
137
|
+
continue;
|
|
138
|
+
const skillMdPath = path.join(claudeSkillsDir, entry.name, "SKILL.md");
|
|
139
|
+
let description = "";
|
|
140
|
+
try {
|
|
141
|
+
const md = fs.readFileSync(skillMdPath, "utf8");
|
|
142
|
+
description = parseSkillFrontmatter(md).description;
|
|
143
|
+
}
|
|
144
|
+
catch { /* no SKILL.md or unreadable */ }
|
|
145
|
+
skills.push({
|
|
146
|
+
name: entry.name,
|
|
147
|
+
description,
|
|
148
|
+
isFideliOSManaged: fideliosSkillNames.has(entry.name),
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
catch { /* ~/.claude/skills/ doesn't exist */ }
|
|
153
|
+
skills.sort((a, b) => a.name.localeCompare(b.name));
|
|
154
|
+
return skills;
|
|
155
|
+
}
|
|
156
|
+
function toJoinRequestResponse(row) {
|
|
157
|
+
const { claimSecretHash: _claimSecretHash, ...safe } = row;
|
|
158
|
+
return safe;
|
|
159
|
+
}
|
|
160
|
+
function isPlainObject(value) {
|
|
161
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
162
|
+
}
|
|
163
|
+
function isLoopbackHost(hostname) {
|
|
164
|
+
const value = hostname.trim().toLowerCase();
|
|
165
|
+
return value === "localhost" || value === "127.0.0.1" || value === "::1";
|
|
166
|
+
}
|
|
167
|
+
function normalizeHostname(value) {
|
|
168
|
+
if (!value)
|
|
169
|
+
return null;
|
|
170
|
+
const trimmed = value.trim();
|
|
171
|
+
if (!trimmed)
|
|
172
|
+
return null;
|
|
173
|
+
if (trimmed.startsWith("[")) {
|
|
174
|
+
const end = trimmed.indexOf("]");
|
|
175
|
+
return end > 1
|
|
176
|
+
? trimmed.slice(1, end).toLowerCase()
|
|
177
|
+
: trimmed.toLowerCase();
|
|
178
|
+
}
|
|
179
|
+
const firstColon = trimmed.indexOf(":");
|
|
180
|
+
if (firstColon > -1)
|
|
181
|
+
return trimmed.slice(0, firstColon).toLowerCase();
|
|
182
|
+
return trimmed.toLowerCase();
|
|
183
|
+
}
|
|
184
|
+
function normalizeHeaderValue(value, depth = 0) {
|
|
185
|
+
const direct = nonEmptyTrimmedString(value);
|
|
186
|
+
if (direct)
|
|
187
|
+
return direct;
|
|
188
|
+
if (!isPlainObject(value) || depth >= 3)
|
|
189
|
+
return null;
|
|
190
|
+
const candidateKeys = [
|
|
191
|
+
"value",
|
|
192
|
+
"token",
|
|
193
|
+
"secret",
|
|
194
|
+
"apiKey",
|
|
195
|
+
"api_key",
|
|
196
|
+
"auth",
|
|
197
|
+
"authToken",
|
|
198
|
+
"auth_token",
|
|
199
|
+
"accessToken",
|
|
200
|
+
"access_token",
|
|
201
|
+
"authorization",
|
|
202
|
+
"bearer",
|
|
203
|
+
"header",
|
|
204
|
+
"raw",
|
|
205
|
+
"text",
|
|
206
|
+
"string"
|
|
207
|
+
];
|
|
208
|
+
for (const key of candidateKeys) {
|
|
209
|
+
if (!Object.prototype.hasOwnProperty.call(value, key))
|
|
210
|
+
continue;
|
|
211
|
+
const normalized = normalizeHeaderValue(value[key], depth + 1);
|
|
212
|
+
if (normalized)
|
|
213
|
+
return normalized;
|
|
214
|
+
}
|
|
215
|
+
const entries = Object.entries(value);
|
|
216
|
+
if (entries.length === 1) {
|
|
217
|
+
const [singleKey, singleValue] = entries[0];
|
|
218
|
+
const normalizedKey = singleKey.trim().toLowerCase();
|
|
219
|
+
if (normalizedKey !== "type" &&
|
|
220
|
+
normalizedKey !== "version" &&
|
|
221
|
+
normalizedKey !== "secretid" &&
|
|
222
|
+
normalizedKey !== "secret_id") {
|
|
223
|
+
const normalized = normalizeHeaderValue(singleValue, depth + 1);
|
|
224
|
+
if (normalized)
|
|
225
|
+
return normalized;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
return null;
|
|
229
|
+
}
|
|
230
|
+
function extractHeaderEntries(input) {
|
|
231
|
+
if (isPlainObject(input)) {
|
|
232
|
+
return Object.entries(input);
|
|
233
|
+
}
|
|
234
|
+
if (!Array.isArray(input)) {
|
|
235
|
+
return [];
|
|
236
|
+
}
|
|
237
|
+
const entries = [];
|
|
238
|
+
for (const item of input) {
|
|
239
|
+
if (Array.isArray(item)) {
|
|
240
|
+
const key = nonEmptyTrimmedString(item[0]);
|
|
241
|
+
if (!key)
|
|
242
|
+
continue;
|
|
243
|
+
entries.push([key, item[1]]);
|
|
244
|
+
continue;
|
|
245
|
+
}
|
|
246
|
+
if (!isPlainObject(item))
|
|
247
|
+
continue;
|
|
248
|
+
const mapped = item;
|
|
249
|
+
const explicitKey = nonEmptyTrimmedString(mapped.key) ??
|
|
250
|
+
nonEmptyTrimmedString(mapped.name) ??
|
|
251
|
+
nonEmptyTrimmedString(mapped.header);
|
|
252
|
+
if (explicitKey) {
|
|
253
|
+
const explicitValue = Object.prototype.hasOwnProperty.call(mapped, "value")
|
|
254
|
+
? mapped.value
|
|
255
|
+
: Object.prototype.hasOwnProperty.call(mapped, "token")
|
|
256
|
+
? mapped.token
|
|
257
|
+
: Object.prototype.hasOwnProperty.call(mapped, "secret")
|
|
258
|
+
? mapped.secret
|
|
259
|
+
: mapped;
|
|
260
|
+
entries.push([explicitKey, explicitValue]);
|
|
261
|
+
continue;
|
|
262
|
+
}
|
|
263
|
+
const singleEntry = Object.entries(mapped);
|
|
264
|
+
if (singleEntry.length === 1) {
|
|
265
|
+
entries.push(singleEntry[0]);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
return entries;
|
|
269
|
+
}
|
|
270
|
+
function normalizeHeaderMap(input) {
|
|
271
|
+
const entries = extractHeaderEntries(input);
|
|
272
|
+
if (entries.length === 0)
|
|
273
|
+
return undefined;
|
|
274
|
+
const out = {};
|
|
275
|
+
for (const [key, value] of entries) {
|
|
276
|
+
const normalizedValue = normalizeHeaderValue(value);
|
|
277
|
+
if (!normalizedValue)
|
|
278
|
+
continue;
|
|
279
|
+
const trimmedKey = key.trim();
|
|
280
|
+
const trimmedValue = normalizedValue.trim();
|
|
281
|
+
if (!trimmedKey || !trimmedValue)
|
|
282
|
+
continue;
|
|
283
|
+
out[trimmedKey] = trimmedValue;
|
|
284
|
+
}
|
|
285
|
+
return Object.keys(out).length > 0 ? out : undefined;
|
|
286
|
+
}
|
|
287
|
+
function nonEmptyTrimmedString(value) {
|
|
288
|
+
if (typeof value !== "string")
|
|
289
|
+
return null;
|
|
290
|
+
const trimmed = value.trim();
|
|
291
|
+
return trimmed.length > 0 ? trimmed : null;
|
|
292
|
+
}
|
|
293
|
+
function headerMapHasKeyIgnoreCase(headers, targetKey) {
|
|
294
|
+
const normalizedTarget = targetKey.trim().toLowerCase();
|
|
295
|
+
return Object.keys(headers).some((key) => key.trim().toLowerCase() === normalizedTarget);
|
|
296
|
+
}
|
|
297
|
+
function headerMapGetIgnoreCase(headers, targetKey) {
|
|
298
|
+
const normalizedTarget = targetKey.trim().toLowerCase();
|
|
299
|
+
const key = Object.keys(headers).find((candidate) => candidate.trim().toLowerCase() === normalizedTarget);
|
|
300
|
+
if (!key)
|
|
301
|
+
return null;
|
|
302
|
+
const value = headers[key];
|
|
303
|
+
return typeof value === "string" ? value : null;
|
|
304
|
+
}
|
|
305
|
+
function tokenFromAuthorizationHeader(rawHeader) {
|
|
306
|
+
const trimmed = nonEmptyTrimmedString(rawHeader);
|
|
307
|
+
if (!trimmed)
|
|
308
|
+
return null;
|
|
309
|
+
const bearerMatch = trimmed.match(/^bearer\s+(.+)$/i);
|
|
310
|
+
if (bearerMatch?.[1]) {
|
|
311
|
+
return nonEmptyTrimmedString(bearerMatch[1]);
|
|
312
|
+
}
|
|
313
|
+
return trimmed;
|
|
314
|
+
}
|
|
315
|
+
function parseBooleanLike(value) {
|
|
316
|
+
if (typeof value === "boolean")
|
|
317
|
+
return value;
|
|
318
|
+
if (typeof value !== "string")
|
|
319
|
+
return null;
|
|
320
|
+
const normalized = value.trim().toLowerCase();
|
|
321
|
+
if (normalized === "true" || normalized === "1")
|
|
322
|
+
return true;
|
|
323
|
+
if (normalized === "false" || normalized === "0")
|
|
324
|
+
return false;
|
|
325
|
+
return null;
|
|
326
|
+
}
|
|
327
|
+
function generateEd25519PrivateKeyPem() {
|
|
328
|
+
const generated = generateKeyPairSync("ed25519");
|
|
329
|
+
return generated.privateKey
|
|
330
|
+
.export({ type: "pkcs8", format: "pem" })
|
|
331
|
+
.toString();
|
|
332
|
+
}
|
|
333
|
+
export function buildJoinDefaultsPayloadForAccept(input) {
|
|
334
|
+
if (input.adapterType !== "openclaw_gateway") {
|
|
335
|
+
return input.defaultsPayload;
|
|
336
|
+
}
|
|
337
|
+
const merged = isPlainObject(input.defaultsPayload)
|
|
338
|
+
? { ...input.defaultsPayload }
|
|
339
|
+
: {};
|
|
340
|
+
if (!nonEmptyTrimmedString(merged.fideliosApiUrl)) {
|
|
341
|
+
const legacyFideliOSApiUrl = nonEmptyTrimmedString(input.fideliosApiUrl);
|
|
342
|
+
if (legacyFideliOSApiUrl)
|
|
343
|
+
merged.fideliosApiUrl = legacyFideliOSApiUrl;
|
|
344
|
+
}
|
|
345
|
+
const mergedHeaders = normalizeHeaderMap(merged.headers) ?? {};
|
|
346
|
+
const inboundOpenClawAuthHeader = nonEmptyTrimmedString(input.inboundOpenClawAuthHeader);
|
|
347
|
+
const inboundOpenClawTokenHeader = nonEmptyTrimmedString(input.inboundOpenClawTokenHeader);
|
|
348
|
+
if (inboundOpenClawTokenHeader &&
|
|
349
|
+
!headerMapHasKeyIgnoreCase(mergedHeaders, "x-openclaw-token")) {
|
|
350
|
+
mergedHeaders["x-openclaw-token"] = inboundOpenClawTokenHeader;
|
|
351
|
+
}
|
|
352
|
+
if (inboundOpenClawAuthHeader &&
|
|
353
|
+
!headerMapHasKeyIgnoreCase(mergedHeaders, "x-openclaw-auth")) {
|
|
354
|
+
mergedHeaders["x-openclaw-auth"] = inboundOpenClawAuthHeader;
|
|
355
|
+
}
|
|
356
|
+
if (Object.keys(mergedHeaders).length > 0) {
|
|
357
|
+
merged.headers = mergedHeaders;
|
|
358
|
+
}
|
|
359
|
+
else {
|
|
360
|
+
delete merged.headers;
|
|
361
|
+
}
|
|
362
|
+
const discoveredToken = headerMapGetIgnoreCase(mergedHeaders, "x-openclaw-token") ??
|
|
363
|
+
headerMapGetIgnoreCase(mergedHeaders, "x-openclaw-auth") ??
|
|
364
|
+
tokenFromAuthorizationHeader(headerMapGetIgnoreCase(mergedHeaders, "authorization"));
|
|
365
|
+
if (discoveredToken &&
|
|
366
|
+
!headerMapHasKeyIgnoreCase(mergedHeaders, "x-openclaw-token")) {
|
|
367
|
+
mergedHeaders["x-openclaw-token"] = discoveredToken;
|
|
368
|
+
}
|
|
369
|
+
return Object.keys(merged).length > 0 ? merged : null;
|
|
370
|
+
}
|
|
371
|
+
export function mergeJoinDefaultsPayloadForReplay(existingDefaultsPayload, nextDefaultsPayload) {
|
|
372
|
+
if (!isPlainObject(existingDefaultsPayload) &&
|
|
373
|
+
!isPlainObject(nextDefaultsPayload)) {
|
|
374
|
+
return nextDefaultsPayload ?? existingDefaultsPayload;
|
|
375
|
+
}
|
|
376
|
+
if (!isPlainObject(existingDefaultsPayload)) {
|
|
377
|
+
return nextDefaultsPayload;
|
|
378
|
+
}
|
|
379
|
+
if (!isPlainObject(nextDefaultsPayload)) {
|
|
380
|
+
return existingDefaultsPayload;
|
|
381
|
+
}
|
|
382
|
+
const merged = {
|
|
383
|
+
...existingDefaultsPayload,
|
|
384
|
+
...nextDefaultsPayload
|
|
385
|
+
};
|
|
386
|
+
const existingHeaders = normalizeHeaderMap(existingDefaultsPayload.headers);
|
|
387
|
+
const nextHeaders = normalizeHeaderMap(nextDefaultsPayload.headers);
|
|
388
|
+
if (existingHeaders || nextHeaders) {
|
|
389
|
+
merged.headers = {
|
|
390
|
+
...(existingHeaders ?? {}),
|
|
391
|
+
...(nextHeaders ?? {})
|
|
392
|
+
};
|
|
393
|
+
}
|
|
394
|
+
else if (Object.prototype.hasOwnProperty.call(merged, "headers")) {
|
|
395
|
+
delete merged.headers;
|
|
396
|
+
}
|
|
397
|
+
return merged;
|
|
398
|
+
}
|
|
399
|
+
export function canReplayOpenClawGatewayInviteAccept(input) {
|
|
400
|
+
if (input.requestType !== "agent" ||
|
|
401
|
+
input.adapterType !== "openclaw_gateway") {
|
|
402
|
+
return false;
|
|
403
|
+
}
|
|
404
|
+
if (!input.existingJoinRequest) {
|
|
405
|
+
return false;
|
|
406
|
+
}
|
|
407
|
+
if (input.existingJoinRequest.requestType !== "agent" ||
|
|
408
|
+
input.existingJoinRequest.adapterType !== "openclaw_gateway") {
|
|
409
|
+
return false;
|
|
410
|
+
}
|
|
411
|
+
return (input.existingJoinRequest.status === "pending_approval" ||
|
|
412
|
+
input.existingJoinRequest.status === "approved");
|
|
413
|
+
}
|
|
414
|
+
function summarizeSecretForLog(value) {
|
|
415
|
+
const trimmed = nonEmptyTrimmedString(value);
|
|
416
|
+
if (!trimmed)
|
|
417
|
+
return null;
|
|
418
|
+
return {
|
|
419
|
+
present: true,
|
|
420
|
+
length: trimmed.length,
|
|
421
|
+
sha256Prefix: hashToken(trimmed).slice(0, 12)
|
|
422
|
+
};
|
|
423
|
+
}
|
|
424
|
+
function summarizeOpenClawGatewayDefaultsForLog(defaultsPayload) {
|
|
425
|
+
const defaults = isPlainObject(defaultsPayload)
|
|
426
|
+
? defaultsPayload
|
|
427
|
+
: null;
|
|
428
|
+
const headers = defaults ? normalizeHeaderMap(defaults.headers) : undefined;
|
|
429
|
+
const gatewayTokenValue = headers
|
|
430
|
+
? headerMapGetIgnoreCase(headers, "x-openclaw-token") ??
|
|
431
|
+
headerMapGetIgnoreCase(headers, "x-openclaw-auth") ??
|
|
432
|
+
tokenFromAuthorizationHeader(headerMapGetIgnoreCase(headers, "authorization"))
|
|
433
|
+
: null;
|
|
434
|
+
return {
|
|
435
|
+
present: Boolean(defaults),
|
|
436
|
+
keys: defaults ? Object.keys(defaults).sort() : [],
|
|
437
|
+
url: defaults ? nonEmptyTrimmedString(defaults.url) : null,
|
|
438
|
+
fideliosApiUrl: defaults
|
|
439
|
+
? nonEmptyTrimmedString(defaults.fideliosApiUrl)
|
|
440
|
+
: null,
|
|
441
|
+
headerKeys: headers ? Object.keys(headers).sort() : [],
|
|
442
|
+
sessionKeyStrategy: defaults
|
|
443
|
+
? nonEmptyTrimmedString(defaults.sessionKeyStrategy)
|
|
444
|
+
: null,
|
|
445
|
+
disableDeviceAuth: defaults
|
|
446
|
+
? parseBooleanLike(defaults.disableDeviceAuth)
|
|
447
|
+
: null,
|
|
448
|
+
waitTimeoutMs: defaults && typeof defaults.waitTimeoutMs === "number"
|
|
449
|
+
? defaults.waitTimeoutMs
|
|
450
|
+
: null,
|
|
451
|
+
devicePrivateKeyPem: defaults
|
|
452
|
+
? summarizeSecretForLog(defaults.devicePrivateKeyPem)
|
|
453
|
+
: null,
|
|
454
|
+
gatewayToken: summarizeSecretForLog(gatewayTokenValue)
|
|
455
|
+
};
|
|
456
|
+
}
|
|
457
|
+
export function normalizeAgentDefaultsForJoin(input) {
|
|
458
|
+
const fatalErrors = [];
|
|
459
|
+
const diagnostics = [];
|
|
460
|
+
if (input.adapterType !== "openclaw_gateway") {
|
|
461
|
+
const normalized = isPlainObject(input.defaultsPayload)
|
|
462
|
+
? input.defaultsPayload
|
|
463
|
+
: null;
|
|
464
|
+
return { normalized, diagnostics, fatalErrors };
|
|
465
|
+
}
|
|
466
|
+
if (!isPlainObject(input.defaultsPayload)) {
|
|
467
|
+
diagnostics.push({
|
|
468
|
+
code: "openclaw_gateway_defaults_missing",
|
|
469
|
+
level: "warn",
|
|
470
|
+
message: "No OpenClaw gateway config was provided in agentDefaultsPayload.",
|
|
471
|
+
hint: "Include agentDefaultsPayload.url and headers.x-openclaw-token for OpenClaw gateway joins."
|
|
472
|
+
});
|
|
473
|
+
fatalErrors.push("agentDefaultsPayload is required for adapterType=openclaw_gateway");
|
|
474
|
+
return {
|
|
475
|
+
normalized: null,
|
|
476
|
+
diagnostics,
|
|
477
|
+
fatalErrors
|
|
478
|
+
};
|
|
479
|
+
}
|
|
480
|
+
const defaults = input.defaultsPayload;
|
|
481
|
+
const normalized = {};
|
|
482
|
+
let gatewayUrl = null;
|
|
483
|
+
const rawGatewayUrl = nonEmptyTrimmedString(defaults.url);
|
|
484
|
+
if (!rawGatewayUrl) {
|
|
485
|
+
diagnostics.push({
|
|
486
|
+
code: "openclaw_gateway_url_missing",
|
|
487
|
+
level: "warn",
|
|
488
|
+
message: "OpenClaw gateway URL is missing.",
|
|
489
|
+
hint: "Set agentDefaultsPayload.url to ws:// or wss:// gateway URL."
|
|
490
|
+
});
|
|
491
|
+
fatalErrors.push("agentDefaultsPayload.url is required");
|
|
492
|
+
}
|
|
493
|
+
else {
|
|
494
|
+
try {
|
|
495
|
+
gatewayUrl = new URL(rawGatewayUrl);
|
|
496
|
+
if (gatewayUrl.protocol !== "ws:" && gatewayUrl.protocol !== "wss:") {
|
|
497
|
+
diagnostics.push({
|
|
498
|
+
code: "openclaw_gateway_url_protocol",
|
|
499
|
+
level: "warn",
|
|
500
|
+
message: `OpenClaw gateway URL must use ws:// or wss:// (got ${gatewayUrl.protocol}).`
|
|
501
|
+
});
|
|
502
|
+
fatalErrors.push("agentDefaultsPayload.url must use ws:// or wss:// for openclaw_gateway");
|
|
503
|
+
}
|
|
504
|
+
else {
|
|
505
|
+
normalized.url = gatewayUrl.toString();
|
|
506
|
+
diagnostics.push({
|
|
507
|
+
code: "openclaw_gateway_url_configured",
|
|
508
|
+
level: "info",
|
|
509
|
+
message: `Gateway endpoint set to ${gatewayUrl.toString()}`
|
|
510
|
+
});
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
catch {
|
|
514
|
+
diagnostics.push({
|
|
515
|
+
code: "openclaw_gateway_url_invalid",
|
|
516
|
+
level: "warn",
|
|
517
|
+
message: `Invalid OpenClaw gateway URL: ${rawGatewayUrl}`
|
|
518
|
+
});
|
|
519
|
+
fatalErrors.push("agentDefaultsPayload.url is not a valid URL");
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
const headers = normalizeHeaderMap(defaults.headers) ?? {};
|
|
523
|
+
const gatewayToken = headerMapGetIgnoreCase(headers, "x-openclaw-token") ??
|
|
524
|
+
headerMapGetIgnoreCase(headers, "x-openclaw-auth") ??
|
|
525
|
+
tokenFromAuthorizationHeader(headerMapGetIgnoreCase(headers, "authorization"));
|
|
526
|
+
if (gatewayToken && !headerMapHasKeyIgnoreCase(headers, "x-openclaw-token")) {
|
|
527
|
+
headers["x-openclaw-token"] = gatewayToken;
|
|
528
|
+
}
|
|
529
|
+
if (Object.keys(headers).length > 0) {
|
|
530
|
+
normalized.headers = headers;
|
|
531
|
+
}
|
|
532
|
+
if (!gatewayToken) {
|
|
533
|
+
diagnostics.push({
|
|
534
|
+
code: "openclaw_gateway_auth_header_missing",
|
|
535
|
+
level: "warn",
|
|
536
|
+
message: "Gateway auth token is missing from agent defaults.",
|
|
537
|
+
hint: "Set agentDefaultsPayload.headers.x-openclaw-token (or legacy x-openclaw-auth)."
|
|
538
|
+
});
|
|
539
|
+
fatalErrors.push("agentDefaultsPayload.headers.x-openclaw-token (or x-openclaw-auth) is required");
|
|
540
|
+
}
|
|
541
|
+
else if (gatewayToken.trim().length < 16) {
|
|
542
|
+
diagnostics.push({
|
|
543
|
+
code: "openclaw_gateway_auth_header_too_short",
|
|
544
|
+
level: "warn",
|
|
545
|
+
message: `Gateway auth token appears too short (${gatewayToken.trim().length} chars).`,
|
|
546
|
+
hint: "Use the full gateway auth token from ~/.openclaw/openclaw.json (typically long random string)."
|
|
547
|
+
});
|
|
548
|
+
fatalErrors.push("agentDefaultsPayload.headers.x-openclaw-token is too short; expected a full gateway token");
|
|
549
|
+
}
|
|
550
|
+
else {
|
|
551
|
+
diagnostics.push({
|
|
552
|
+
code: "openclaw_gateway_auth_header_configured",
|
|
553
|
+
level: "info",
|
|
554
|
+
message: "Gateway auth token configured."
|
|
555
|
+
});
|
|
556
|
+
}
|
|
557
|
+
if (isPlainObject(defaults.payloadTemplate)) {
|
|
558
|
+
normalized.payloadTemplate = defaults.payloadTemplate;
|
|
559
|
+
}
|
|
560
|
+
const parsedDisableDeviceAuth = parseBooleanLike(defaults.disableDeviceAuth);
|
|
561
|
+
const disableDeviceAuth = parsedDisableDeviceAuth === true;
|
|
562
|
+
if (parsedDisableDeviceAuth !== null) {
|
|
563
|
+
normalized.disableDeviceAuth = parsedDisableDeviceAuth;
|
|
564
|
+
}
|
|
565
|
+
const configuredDevicePrivateKeyPem = nonEmptyTrimmedString(defaults.devicePrivateKeyPem);
|
|
566
|
+
if (configuredDevicePrivateKeyPem) {
|
|
567
|
+
normalized.devicePrivateKeyPem = configuredDevicePrivateKeyPem;
|
|
568
|
+
diagnostics.push({
|
|
569
|
+
code: "openclaw_gateway_device_key_configured",
|
|
570
|
+
level: "info",
|
|
571
|
+
message: "Gateway device key configured. Pairing approvals should persist for this agent."
|
|
572
|
+
});
|
|
573
|
+
}
|
|
574
|
+
else if (!disableDeviceAuth) {
|
|
575
|
+
try {
|
|
576
|
+
normalized.devicePrivateKeyPem = generateEd25519PrivateKeyPem();
|
|
577
|
+
diagnostics.push({
|
|
578
|
+
code: "openclaw_gateway_device_key_generated",
|
|
579
|
+
level: "info",
|
|
580
|
+
message: "Generated persistent gateway device key for this join. Pairing approvals should persist for this agent."
|
|
581
|
+
});
|
|
582
|
+
}
|
|
583
|
+
catch (err) {
|
|
584
|
+
diagnostics.push({
|
|
585
|
+
code: "openclaw_gateway_device_key_generate_failed",
|
|
586
|
+
level: "warn",
|
|
587
|
+
message: `Failed to generate gateway device key: ${err instanceof Error ? err.message : String(err)}`,
|
|
588
|
+
hint: "Set agentDefaultsPayload.devicePrivateKeyPem explicitly or set disableDeviceAuth=true."
|
|
589
|
+
});
|
|
590
|
+
fatalErrors.push("Failed to generate gateway device key. Set devicePrivateKeyPem or disableDeviceAuth=true.");
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
const waitTimeoutMs = typeof defaults.waitTimeoutMs === "number" &&
|
|
594
|
+
Number.isFinite(defaults.waitTimeoutMs)
|
|
595
|
+
? Math.floor(defaults.waitTimeoutMs)
|
|
596
|
+
: typeof defaults.waitTimeoutMs === "string"
|
|
597
|
+
? Number.parseInt(defaults.waitTimeoutMs.trim(), 10)
|
|
598
|
+
: NaN;
|
|
599
|
+
if (Number.isFinite(waitTimeoutMs) && waitTimeoutMs > 0) {
|
|
600
|
+
normalized.waitTimeoutMs = waitTimeoutMs;
|
|
601
|
+
}
|
|
602
|
+
const timeoutSec = typeof defaults.timeoutSec === "number" && Number.isFinite(defaults.timeoutSec)
|
|
603
|
+
? Math.floor(defaults.timeoutSec)
|
|
604
|
+
: typeof defaults.timeoutSec === "string"
|
|
605
|
+
? Number.parseInt(defaults.timeoutSec.trim(), 10)
|
|
606
|
+
: NaN;
|
|
607
|
+
if (Number.isFinite(timeoutSec) && timeoutSec > 0) {
|
|
608
|
+
normalized.timeoutSec = timeoutSec;
|
|
609
|
+
}
|
|
610
|
+
const sessionKeyStrategy = nonEmptyTrimmedString(defaults.sessionKeyStrategy);
|
|
611
|
+
if (sessionKeyStrategy === "fixed" ||
|
|
612
|
+
sessionKeyStrategy === "issue" ||
|
|
613
|
+
sessionKeyStrategy === "run") {
|
|
614
|
+
normalized.sessionKeyStrategy = sessionKeyStrategy;
|
|
615
|
+
}
|
|
616
|
+
const sessionKey = nonEmptyTrimmedString(defaults.sessionKey);
|
|
617
|
+
if (sessionKey) {
|
|
618
|
+
normalized.sessionKey = sessionKey;
|
|
619
|
+
}
|
|
620
|
+
const role = nonEmptyTrimmedString(defaults.role);
|
|
621
|
+
if (role) {
|
|
622
|
+
normalized.role = role;
|
|
623
|
+
}
|
|
624
|
+
if (Array.isArray(defaults.scopes)) {
|
|
625
|
+
const scopes = defaults.scopes
|
|
626
|
+
.filter((entry) => typeof entry === "string")
|
|
627
|
+
.map((entry) => entry.trim())
|
|
628
|
+
.filter(Boolean);
|
|
629
|
+
if (scopes.length > 0) {
|
|
630
|
+
normalized.scopes = scopes;
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
const rawFideliOSApiUrl = typeof defaults.fideliosApiUrl === "string"
|
|
634
|
+
? defaults.fideliosApiUrl.trim()
|
|
635
|
+
: "";
|
|
636
|
+
if (rawFideliOSApiUrl) {
|
|
637
|
+
try {
|
|
638
|
+
const parsedFideliOSApiUrl = new URL(rawFideliOSApiUrl);
|
|
639
|
+
if (parsedFideliOSApiUrl.protocol !== "http:" &&
|
|
640
|
+
parsedFideliOSApiUrl.protocol !== "https:") {
|
|
641
|
+
diagnostics.push({
|
|
642
|
+
code: "openclaw_gateway_fidelios_api_url_protocol",
|
|
643
|
+
level: "warn",
|
|
644
|
+
message: `fideliosApiUrl must use http:// or https:// (got ${parsedFideliOSApiUrl.protocol}).`
|
|
645
|
+
});
|
|
646
|
+
}
|
|
647
|
+
else {
|
|
648
|
+
normalized.fideliosApiUrl = parsedFideliOSApiUrl.toString();
|
|
649
|
+
diagnostics.push({
|
|
650
|
+
code: "openclaw_gateway_fidelios_api_url_configured",
|
|
651
|
+
level: "info",
|
|
652
|
+
message: `fideliosApiUrl set to ${parsedFideliOSApiUrl.toString()}`
|
|
653
|
+
});
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
catch {
|
|
657
|
+
diagnostics.push({
|
|
658
|
+
code: "openclaw_gateway_fidelios_api_url_invalid",
|
|
659
|
+
level: "warn",
|
|
660
|
+
message: `Invalid fideliosApiUrl: ${rawFideliOSApiUrl}`
|
|
661
|
+
});
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
return { normalized, diagnostics, fatalErrors };
|
|
665
|
+
}
|
|
666
|
+
function toInviteSummaryResponse(req, token, invite) {
|
|
667
|
+
const baseUrl = requestBaseUrl(req);
|
|
668
|
+
const onboardingPath = `/api/invites/${token}/onboarding`;
|
|
669
|
+
const onboardingTextPath = `/api/invites/${token}/onboarding.txt`;
|
|
670
|
+
const inviteMessage = extractInviteMessage(invite);
|
|
671
|
+
return {
|
|
672
|
+
id: invite.id,
|
|
673
|
+
companyId: invite.companyId,
|
|
674
|
+
inviteType: invite.inviteType,
|
|
675
|
+
allowedJoinTypes: invite.allowedJoinTypes,
|
|
676
|
+
expiresAt: invite.expiresAt,
|
|
677
|
+
onboardingPath,
|
|
678
|
+
onboardingUrl: baseUrl ? `${baseUrl}${onboardingPath}` : onboardingPath,
|
|
679
|
+
onboardingTextPath,
|
|
680
|
+
onboardingTextUrl: baseUrl
|
|
681
|
+
? `${baseUrl}${onboardingTextPath}`
|
|
682
|
+
: onboardingTextPath,
|
|
683
|
+
skillIndexPath: "/api/skills/index",
|
|
684
|
+
skillIndexUrl: baseUrl
|
|
685
|
+
? `${baseUrl}/api/skills/index`
|
|
686
|
+
: "/api/skills/index",
|
|
687
|
+
inviteMessage
|
|
688
|
+
};
|
|
689
|
+
}
|
|
690
|
+
function buildOnboardingDiscoveryDiagnostics(input) {
|
|
691
|
+
const diagnostics = [];
|
|
692
|
+
let apiHost = null;
|
|
693
|
+
if (input.apiBaseUrl) {
|
|
694
|
+
try {
|
|
695
|
+
apiHost = normalizeHostname(new URL(input.apiBaseUrl).hostname);
|
|
696
|
+
}
|
|
697
|
+
catch {
|
|
698
|
+
apiHost = null;
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
const bindHost = normalizeHostname(input.bindHost);
|
|
702
|
+
const allowSet = new Set(input.allowedHostnames
|
|
703
|
+
.map((entry) => normalizeHostname(entry))
|
|
704
|
+
.filter((entry) => Boolean(entry)));
|
|
705
|
+
if (apiHost && isLoopbackHost(apiHost)) {
|
|
706
|
+
diagnostics.push({
|
|
707
|
+
code: "openclaw_onboarding_api_loopback",
|
|
708
|
+
level: "warn",
|
|
709
|
+
message: "Onboarding URL resolves to loopback hostname. Remote OpenClaw agents cannot reach localhost on your FideliOS host.",
|
|
710
|
+
hint: "Use a reachable hostname/IP (for example Tailscale hostname, Docker host alias, or public domain)."
|
|
711
|
+
});
|
|
712
|
+
}
|
|
713
|
+
if (input.deploymentMode === "authenticated" &&
|
|
714
|
+
input.deploymentExposure === "private" &&
|
|
715
|
+
(!bindHost || isLoopbackHost(bindHost))) {
|
|
716
|
+
diagnostics.push({
|
|
717
|
+
code: "openclaw_onboarding_private_loopback_bind",
|
|
718
|
+
level: "warn",
|
|
719
|
+
message: "FideliOS is bound to loopback in authenticated/private mode.",
|
|
720
|
+
hint: "Run with a reachable bind host or use pnpm dev --tailscale-auth for private-network onboarding."
|
|
721
|
+
});
|
|
722
|
+
}
|
|
723
|
+
if (input.deploymentMode === "authenticated" &&
|
|
724
|
+
input.deploymentExposure === "private" &&
|
|
725
|
+
apiHost &&
|
|
726
|
+
!isLoopbackHost(apiHost) &&
|
|
727
|
+
allowSet.size > 0 &&
|
|
728
|
+
!allowSet.has(apiHost)) {
|
|
729
|
+
diagnostics.push({
|
|
730
|
+
code: "openclaw_onboarding_private_host_not_allowed",
|
|
731
|
+
level: "warn",
|
|
732
|
+
message: `Onboarding host "${apiHost}" is not in allowed hostnames for authenticated/private mode.`,
|
|
733
|
+
hint: `Run pnpm fidelios allowed-hostname ${apiHost}`
|
|
734
|
+
});
|
|
735
|
+
}
|
|
736
|
+
return diagnostics;
|
|
737
|
+
}
|
|
738
|
+
function buildOnboardingConnectionCandidates(input) {
|
|
739
|
+
let base = null;
|
|
740
|
+
try {
|
|
741
|
+
if (input.apiBaseUrl) {
|
|
742
|
+
base = new URL(input.apiBaseUrl);
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
catch {
|
|
746
|
+
base = null;
|
|
747
|
+
}
|
|
748
|
+
const protocol = base?.protocol ?? "http:";
|
|
749
|
+
const port = base?.port ? `:${base.port}` : "";
|
|
750
|
+
const candidates = new Set();
|
|
751
|
+
if (base) {
|
|
752
|
+
candidates.add(base.origin);
|
|
753
|
+
}
|
|
754
|
+
const bindHost = normalizeHostname(input.bindHost);
|
|
755
|
+
if (bindHost && !isLoopbackHost(bindHost)) {
|
|
756
|
+
candidates.add(`${protocol}//${bindHost}${port}`);
|
|
757
|
+
}
|
|
758
|
+
for (const rawHost of input.allowedHostnames) {
|
|
759
|
+
const host = normalizeHostname(rawHost);
|
|
760
|
+
if (!host)
|
|
761
|
+
continue;
|
|
762
|
+
candidates.add(`${protocol}//${host}${port}`);
|
|
763
|
+
}
|
|
764
|
+
if (base && isLoopbackHost(base.hostname)) {
|
|
765
|
+
candidates.add(`${protocol}//host.docker.internal${port}`);
|
|
766
|
+
}
|
|
767
|
+
return Array.from(candidates);
|
|
768
|
+
}
|
|
769
|
+
function buildInviteOnboardingManifest(req, token, invite, opts) {
|
|
770
|
+
const baseUrl = requestBaseUrl(req);
|
|
771
|
+
const skillPath = "/api/skills/fidelios";
|
|
772
|
+
const skillUrl = baseUrl ? `${baseUrl}${skillPath}` : skillPath;
|
|
773
|
+
const registrationEndpointPath = `/api/invites/${token}/accept`;
|
|
774
|
+
const registrationEndpointUrl = baseUrl
|
|
775
|
+
? `${baseUrl}${registrationEndpointPath}`
|
|
776
|
+
: registrationEndpointPath;
|
|
777
|
+
const onboardingTextPath = `/api/invites/${token}/onboarding.txt`;
|
|
778
|
+
const onboardingTextUrl = baseUrl
|
|
779
|
+
? `${baseUrl}${onboardingTextPath}`
|
|
780
|
+
: onboardingTextPath;
|
|
781
|
+
const discoveryDiagnostics = buildOnboardingDiscoveryDiagnostics({
|
|
782
|
+
apiBaseUrl: baseUrl,
|
|
783
|
+
deploymentMode: opts.deploymentMode,
|
|
784
|
+
deploymentExposure: opts.deploymentExposure,
|
|
785
|
+
bindHost: opts.bindHost,
|
|
786
|
+
allowedHostnames: opts.allowedHostnames
|
|
787
|
+
});
|
|
788
|
+
const connectionCandidates = buildOnboardingConnectionCandidates({
|
|
789
|
+
apiBaseUrl: baseUrl,
|
|
790
|
+
bindHost: opts.bindHost,
|
|
791
|
+
allowedHostnames: opts.allowedHostnames
|
|
792
|
+
});
|
|
793
|
+
return {
|
|
794
|
+
invite: toInviteSummaryResponse(req, token, invite),
|
|
795
|
+
onboarding: {
|
|
796
|
+
instructions: "Join as an OpenClaw Gateway agent, save your one-time claim secret, wait for board approval, then claim your API key. Save the claim response token to ~/.openclaw/workspace/fidelios-claimed-api-key.json and load FIDELIOS_API_KEY from that file before starting heartbeat loops. You MUST submit adapterType='openclaw_gateway', set agentDefaultsPayload.url to your ws:// or wss:// OpenClaw gateway endpoint, and include agentDefaultsPayload.headers.x-openclaw-token (or legacy x-openclaw-auth).",
|
|
797
|
+
inviteMessage: extractInviteMessage(invite),
|
|
798
|
+
recommendedAdapterType: "openclaw_gateway",
|
|
799
|
+
requiredFields: {
|
|
800
|
+
requestType: "agent",
|
|
801
|
+
agentName: "Display name for this agent",
|
|
802
|
+
adapterType: "Use 'openclaw_gateway' for OpenClaw Gateway agents",
|
|
803
|
+
capabilities: "Optional capability summary",
|
|
804
|
+
agentDefaultsPayload: "Adapter config for OpenClaw gateway. MUST include url (ws:// or wss://) and headers.x-openclaw-token (or legacy x-openclaw-auth). Optional fields: fideliosApiUrl, waitTimeoutMs, sessionKeyStrategy, sessionKey, role, scopes, disableDeviceAuth, devicePrivateKeyPem."
|
|
805
|
+
},
|
|
806
|
+
registrationEndpoint: {
|
|
807
|
+
method: "POST",
|
|
808
|
+
path: registrationEndpointPath,
|
|
809
|
+
url: registrationEndpointUrl
|
|
810
|
+
},
|
|
811
|
+
claimEndpointTemplate: {
|
|
812
|
+
method: "POST",
|
|
813
|
+
path: "/api/join-requests/{requestId}/claim-api-key",
|
|
814
|
+
body: {
|
|
815
|
+
claimSecret: "one-time claim secret returned when the join request is created"
|
|
816
|
+
}
|
|
817
|
+
},
|
|
818
|
+
connectivity: {
|
|
819
|
+
deploymentMode: opts.deploymentMode,
|
|
820
|
+
deploymentExposure: opts.deploymentExposure,
|
|
821
|
+
bindHost: opts.bindHost,
|
|
822
|
+
allowedHostnames: opts.allowedHostnames,
|
|
823
|
+
connectionCandidates,
|
|
824
|
+
diagnostics: discoveryDiagnostics,
|
|
825
|
+
guidance: opts.deploymentMode === "authenticated" &&
|
|
826
|
+
opts.deploymentExposure === "private"
|
|
827
|
+
? "If OpenClaw runs on another machine, ensure the FideliOS hostname is reachable and allowed via `pnpm fidelios allowed-hostname <host>`."
|
|
828
|
+
: "Ensure OpenClaw can reach this FideliOS API base URL for invite, claim, and skill bootstrap calls."
|
|
829
|
+
},
|
|
830
|
+
textInstructions: {
|
|
831
|
+
path: onboardingTextPath,
|
|
832
|
+
url: onboardingTextUrl,
|
|
833
|
+
contentType: "text/plain"
|
|
834
|
+
},
|
|
835
|
+
skill: {
|
|
836
|
+
name: "fidelios",
|
|
837
|
+
path: skillPath,
|
|
838
|
+
url: skillUrl,
|
|
839
|
+
installPath: "~/.openclaw/skills/fidelios/SKILL.md"
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
};
|
|
843
|
+
}
|
|
844
|
+
export function buildInviteOnboardingTextDocument(req, token, invite, opts) {
|
|
845
|
+
const manifest = buildInviteOnboardingManifest(req, token, invite, opts);
|
|
846
|
+
const onboarding = manifest.onboarding;
|
|
847
|
+
const diagnostics = Array.isArray(onboarding.connectivity?.diagnostics)
|
|
848
|
+
? onboarding.connectivity.diagnostics
|
|
849
|
+
: [];
|
|
850
|
+
const lines = [];
|
|
851
|
+
const appendBlock = (block) => {
|
|
852
|
+
const trimmed = block.replace(/^\n/, "").replace(/\n\s*$/, "");
|
|
853
|
+
const lineIndentation = trimmed
|
|
854
|
+
.split("\n")
|
|
855
|
+
.filter((line) => line.trim().length > 0)
|
|
856
|
+
.map((line) => line.match(/^(\s*)/)?.[0].length ?? 0);
|
|
857
|
+
const minIndent = lineIndentation.length > 0 ? Math.min(...lineIndentation) : 0;
|
|
858
|
+
for (const line of trimmed.split("\n")) {
|
|
859
|
+
lines.push(line.slice(minIndent));
|
|
860
|
+
}
|
|
861
|
+
};
|
|
862
|
+
appendBlock(`
|
|
863
|
+
# FideliOS OpenClaw Gateway Onboarding
|
|
864
|
+
|
|
865
|
+
This document is meant to be readable by both humans and agents.
|
|
866
|
+
|
|
867
|
+
## Invite
|
|
868
|
+
- inviteType: ${invite.inviteType}
|
|
869
|
+
- allowedJoinTypes: ${invite.allowedJoinTypes}
|
|
870
|
+
- expiresAt: ${invite.expiresAt.toISOString()}
|
|
871
|
+
`);
|
|
872
|
+
if (onboarding.inviteMessage) {
|
|
873
|
+
appendBlock(`
|
|
874
|
+
## Message from inviter
|
|
875
|
+
${onboarding.inviteMessage}
|
|
876
|
+
`);
|
|
877
|
+
}
|
|
878
|
+
appendBlock(`
|
|
879
|
+
## Step 0
|
|
880
|
+
|
|
881
|
+
Get the OpenClaw gateway auth token (THIS MUST BE SENT)
|
|
882
|
+
Token lives in:
|
|
883
|
+
|
|
884
|
+
~/.openclaw/openclaw.json -> gateway.auth.token
|
|
885
|
+
Extract:
|
|
886
|
+
|
|
887
|
+
TOKEN="$(node -p 'require(process.env.HOME+\"/.openclaw/openclaw.json\").gateway.auth.token')"
|
|
888
|
+
test -n "$TOKEN" || (echo "Missing TOKEN" && exit 1)
|
|
889
|
+
test "\${#TOKEN}" -ge 16 || (echo "Gateway token unexpectedly short (\${#TOKEN})" && exit 1)
|
|
890
|
+
|
|
891
|
+
3) IMPORTANT: Don't accidentally drop the token when generating JSON
|
|
892
|
+
If you build JSON with Node, pass the token explicitly (argv), don't rely on an un-exported env var.
|
|
893
|
+
|
|
894
|
+
Safe payload build looks sort of like this (substitute where necessary):
|
|
895
|
+
|
|
896
|
+
BODY="$(node -e '
|
|
897
|
+
const token = process.argv[1];
|
|
898
|
+
if (!token) process.exit(2);
|
|
899
|
+
const body = {
|
|
900
|
+
requestType: "agent",
|
|
901
|
+
agentName: "OpenClaw",
|
|
902
|
+
adapterType: "openclaw_gateway",
|
|
903
|
+
capabilities: "OpenClaw agent adapter",
|
|
904
|
+
agentDefaultsPayload: {
|
|
905
|
+
url: "ws://127.0.0.1:18789",
|
|
906
|
+
fideliosApiUrl: "http://host.docker.internal:3100",
|
|
907
|
+
headers: { "x-openclaw-token": token },
|
|
908
|
+
waitTimeoutMs: 120000,
|
|
909
|
+
sessionKeyStrategy: "issue",
|
|
910
|
+
role: "operator",
|
|
911
|
+
scopes: ["operator.admin"]
|
|
912
|
+
}
|
|
913
|
+
};
|
|
914
|
+
process.stdout.write(JSON.stringify(body));
|
|
915
|
+
' "$TOKEN")"
|
|
916
|
+
|
|
917
|
+
## Step 1: Submit agent join request
|
|
918
|
+
${onboarding.registrationEndpoint.method} ${onboarding.registrationEndpoint.url}
|
|
919
|
+
|
|
920
|
+
IMPORTANT: You MUST include agentDefaultsPayload.headers.x-openclaw-token with your gateway token.
|
|
921
|
+
Legacy x-openclaw-auth is also accepted, but x-openclaw-token is preferred.
|
|
922
|
+
Use adapterType "openclaw_gateway" and a ws:// or wss:// gateway URL.
|
|
923
|
+
Pairing mode requirement:
|
|
924
|
+
- Keep device auth enabled (recommended). If devicePrivateKeyPem is omitted, FideliOS generates and persists one during join so pairing approvals are stable.
|
|
925
|
+
- You may set disableDeviceAuth=true only for special environments that cannot support pairing.
|
|
926
|
+
- First run may return "pairing required" once; approve the pending pairing request in OpenClaw, then retry.
|
|
927
|
+
Do NOT use /v1/responses or /hooks/* in this gateway join flow.
|
|
928
|
+
|
|
929
|
+
Body (JSON):
|
|
930
|
+
{
|
|
931
|
+
"requestType": "agent",
|
|
932
|
+
"agentName": "My OpenClaw Agent",
|
|
933
|
+
"adapterType": "openclaw_gateway",
|
|
934
|
+
"capabilities": "Optional summary",
|
|
935
|
+
"agentDefaultsPayload": {
|
|
936
|
+
"url": "wss://your-openclaw-gateway.example",
|
|
937
|
+
"fideliosApiUrl": "https://fidelios-hostname-your-agent-can-reach:3100",
|
|
938
|
+
"headers": { "x-openclaw-token": "replace-me" },
|
|
939
|
+
"waitTimeoutMs": 120000,
|
|
940
|
+
"sessionKeyStrategy": "issue",
|
|
941
|
+
"role": "operator",
|
|
942
|
+
"scopes": ["operator.admin"]
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
Expected response includes:
|
|
947
|
+
- request id
|
|
948
|
+
- one-time claimSecret
|
|
949
|
+
- claimApiKeyPath
|
|
950
|
+
|
|
951
|
+
## Step 2: Wait for board approval
|
|
952
|
+
The board approves the join request in FideliOS before key claim is allowed.
|
|
953
|
+
|
|
954
|
+
## Step 3: Claim API key (one-time)
|
|
955
|
+
${onboarding.claimEndpointTemplate.method} /api/join-requests/{requestId}/claim-api-key
|
|
956
|
+
|
|
957
|
+
Body (JSON):
|
|
958
|
+
{
|
|
959
|
+
"claimSecret": "<one-time-claim-secret>"
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
On successful claim, save the full JSON response to:
|
|
963
|
+
|
|
964
|
+
- ~/.openclaw/workspace/fidelios-claimed-api-key.json
|
|
965
|
+
chmod 600 ~/.openclaw/workspace/fidelios-claimed-api-key.json
|
|
966
|
+
|
|
967
|
+
And set the FIDELIOS_API_KEY and FIDELIOS_API_URL in your environment variables as specified here:
|
|
968
|
+
https://docs.openclaw.ai/help/environment
|
|
969
|
+
|
|
970
|
+
e.g.
|
|
971
|
+
|
|
972
|
+
{
|
|
973
|
+
env: {
|
|
974
|
+
FIDELIOS_API_KEY: "...",
|
|
975
|
+
FIDELIOS_API_URL: "...",
|
|
976
|
+
},
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
Then set FIDELIOS_API_KEY and FIDELIOS_API_URL from the saved token field for every heartbeat run.
|
|
980
|
+
|
|
981
|
+
Important:
|
|
982
|
+
- claim secrets expire
|
|
983
|
+
- claim secrets are single-use
|
|
984
|
+
- claim fails before board approval
|
|
985
|
+
|
|
986
|
+
## Step 4: Install FideliOS skill in OpenClaw
|
|
987
|
+
GET ${onboarding.skill.url}
|
|
988
|
+
Install path: ${onboarding.skill.installPath}
|
|
989
|
+
|
|
990
|
+
Be sure to prepend your FIDELIOS_API_URL to the top of your skill and note the path to your FIDELIOS_API_URL
|
|
991
|
+
|
|
992
|
+
## Text onboarding URL
|
|
993
|
+
${onboarding.textInstructions.url}
|
|
994
|
+
|
|
995
|
+
## Connectivity guidance
|
|
996
|
+
${onboarding.connectivity?.guidance ??
|
|
997
|
+
"Ensure FideliOS is reachable from your OpenClaw runtime."}
|
|
998
|
+
`);
|
|
999
|
+
const connectionCandidates = Array.isArray(onboarding.connectivity?.connectionCandidates)
|
|
1000
|
+
? onboarding.connectivity.connectionCandidates.filter((entry) => Boolean(entry))
|
|
1001
|
+
: [];
|
|
1002
|
+
if (connectionCandidates.length > 0) {
|
|
1003
|
+
lines.push("## Suggested FideliOS base URLs to try");
|
|
1004
|
+
for (const candidate of connectionCandidates) {
|
|
1005
|
+
lines.push(`- ${candidate}`);
|
|
1006
|
+
}
|
|
1007
|
+
appendBlock(`
|
|
1008
|
+
|
|
1009
|
+
Test each candidate with:
|
|
1010
|
+
- GET <candidate>/api/health
|
|
1011
|
+
- set the first reachable candidate as agentDefaultsPayload.fideliosApiUrl when submitting your join request
|
|
1012
|
+
|
|
1013
|
+
If none are reachable: ask your human operator for a reachable hostname/address and help them update network configuration.
|
|
1014
|
+
For authenticated/private mode, they may need:
|
|
1015
|
+
- pnpm fidelios allowed-hostname <host>
|
|
1016
|
+
- then restart FideliOS and retry onboarding.
|
|
1017
|
+
`);
|
|
1018
|
+
}
|
|
1019
|
+
if (diagnostics.length > 0) {
|
|
1020
|
+
lines.push("## Connectivity diagnostics");
|
|
1021
|
+
for (const diag of diagnostics) {
|
|
1022
|
+
lines.push(`- [${diag.level}] ${diag.message}`);
|
|
1023
|
+
if (diag.hint)
|
|
1024
|
+
lines.push(` hint: ${diag.hint}`);
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
appendBlock(`
|
|
1028
|
+
|
|
1029
|
+
## Helpful endpoints
|
|
1030
|
+
${onboarding.registrationEndpoint.path}
|
|
1031
|
+
${onboarding.claimEndpointTemplate.path}
|
|
1032
|
+
${onboarding.skill.path}
|
|
1033
|
+
${manifest.invite.onboardingPath}
|
|
1034
|
+
`);
|
|
1035
|
+
return `${lines.join("\n")}\n`;
|
|
1036
|
+
}
|
|
1037
|
+
function extractInviteMessage(invite) {
|
|
1038
|
+
const rawDefaults = invite.defaultsPayload;
|
|
1039
|
+
if (!rawDefaults ||
|
|
1040
|
+
typeof rawDefaults !== "object" ||
|
|
1041
|
+
Array.isArray(rawDefaults)) {
|
|
1042
|
+
return null;
|
|
1043
|
+
}
|
|
1044
|
+
const rawMessage = rawDefaults.agentMessage;
|
|
1045
|
+
if (typeof rawMessage !== "string") {
|
|
1046
|
+
return null;
|
|
1047
|
+
}
|
|
1048
|
+
const trimmed = rawMessage.trim();
|
|
1049
|
+
return trimmed.length ? trimmed : null;
|
|
1050
|
+
}
|
|
1051
|
+
function mergeInviteDefaults(defaultsPayload, agentMessage) {
|
|
1052
|
+
const merged = defaultsPayload && typeof defaultsPayload === "object"
|
|
1053
|
+
? { ...defaultsPayload }
|
|
1054
|
+
: {};
|
|
1055
|
+
if (agentMessage) {
|
|
1056
|
+
merged.agentMessage = agentMessage;
|
|
1057
|
+
}
|
|
1058
|
+
return Object.keys(merged).length ? merged : null;
|
|
1059
|
+
}
|
|
1060
|
+
function requestIp(req) {
|
|
1061
|
+
const forwarded = req.header("x-forwarded-for");
|
|
1062
|
+
if (forwarded) {
|
|
1063
|
+
const first = forwarded.split(",")[0]?.trim();
|
|
1064
|
+
if (first)
|
|
1065
|
+
return first;
|
|
1066
|
+
}
|
|
1067
|
+
return req.ip || "unknown";
|
|
1068
|
+
}
|
|
1069
|
+
function inviteExpired(invite) {
|
|
1070
|
+
return invite.expiresAt.getTime() <= Date.now();
|
|
1071
|
+
}
|
|
1072
|
+
function isLocalImplicit(req) {
|
|
1073
|
+
return req.actor.type === "board" && req.actor.source === "local_implicit";
|
|
1074
|
+
}
|
|
1075
|
+
async function resolveActorEmail(db, req) {
|
|
1076
|
+
if (isLocalImplicit(req))
|
|
1077
|
+
return "local@fidelios.local";
|
|
1078
|
+
const userId = req.actor.userId;
|
|
1079
|
+
if (!userId)
|
|
1080
|
+
return null;
|
|
1081
|
+
const user = await db
|
|
1082
|
+
.select({ email: authUsers.email })
|
|
1083
|
+
.from(authUsers)
|
|
1084
|
+
.where(eq(authUsers.id, userId))
|
|
1085
|
+
.then((rows) => rows[0] ?? null);
|
|
1086
|
+
return user?.email ?? null;
|
|
1087
|
+
}
|
|
1088
|
+
function grantsFromDefaults(defaultsPayload, key) {
|
|
1089
|
+
if (!defaultsPayload || typeof defaultsPayload !== "object")
|
|
1090
|
+
return [];
|
|
1091
|
+
const scoped = defaultsPayload[key];
|
|
1092
|
+
if (!scoped || typeof scoped !== "object")
|
|
1093
|
+
return [];
|
|
1094
|
+
const grants = scoped.grants;
|
|
1095
|
+
if (!Array.isArray(grants))
|
|
1096
|
+
return [];
|
|
1097
|
+
const validPermissionKeys = new Set(PERMISSION_KEYS);
|
|
1098
|
+
const result = [];
|
|
1099
|
+
for (const item of grants) {
|
|
1100
|
+
if (!item || typeof item !== "object")
|
|
1101
|
+
continue;
|
|
1102
|
+
const record = item;
|
|
1103
|
+
if (typeof record.permissionKey !== "string")
|
|
1104
|
+
continue;
|
|
1105
|
+
if (!validPermissionKeys.has(record.permissionKey))
|
|
1106
|
+
continue;
|
|
1107
|
+
result.push({
|
|
1108
|
+
permissionKey: record.permissionKey,
|
|
1109
|
+
scope: record.scope &&
|
|
1110
|
+
typeof record.scope === "object" &&
|
|
1111
|
+
!Array.isArray(record.scope)
|
|
1112
|
+
? record.scope
|
|
1113
|
+
: null
|
|
1114
|
+
});
|
|
1115
|
+
}
|
|
1116
|
+
return result;
|
|
1117
|
+
}
|
|
1118
|
+
export function agentJoinGrantsFromDefaults(defaultsPayload) {
|
|
1119
|
+
const grants = grantsFromDefaults(defaultsPayload, "agent");
|
|
1120
|
+
if (grants.some((grant) => grant.permissionKey === "tasks:assign")) {
|
|
1121
|
+
return grants;
|
|
1122
|
+
}
|
|
1123
|
+
return [
|
|
1124
|
+
...grants,
|
|
1125
|
+
{
|
|
1126
|
+
permissionKey: "tasks:assign",
|
|
1127
|
+
scope: null
|
|
1128
|
+
}
|
|
1129
|
+
];
|
|
1130
|
+
}
|
|
1131
|
+
export function resolveJoinRequestAgentManagerId(candidates) {
|
|
1132
|
+
const ceoCandidates = candidates.filter((candidate) => candidate.role === "ceo");
|
|
1133
|
+
if (ceoCandidates.length === 0)
|
|
1134
|
+
return null;
|
|
1135
|
+
const rootCeo = ceoCandidates.find((candidate) => candidate.reportsTo === null);
|
|
1136
|
+
return (rootCeo ?? ceoCandidates[0] ?? null)?.id ?? null;
|
|
1137
|
+
}
|
|
1138
|
+
function isInviteTokenHashCollisionError(error) {
|
|
1139
|
+
const candidates = [
|
|
1140
|
+
error,
|
|
1141
|
+
error?.cause ?? null
|
|
1142
|
+
];
|
|
1143
|
+
for (const candidate of candidates) {
|
|
1144
|
+
if (!candidate || typeof candidate !== "object")
|
|
1145
|
+
continue;
|
|
1146
|
+
const code = "code" in candidate && typeof candidate.code === "string"
|
|
1147
|
+
? candidate.code
|
|
1148
|
+
: null;
|
|
1149
|
+
const message = "message" in candidate && typeof candidate.message === "string"
|
|
1150
|
+
? candidate.message
|
|
1151
|
+
: "";
|
|
1152
|
+
const constraint = "constraint" in candidate && typeof candidate.constraint === "string"
|
|
1153
|
+
? candidate.constraint
|
|
1154
|
+
: null;
|
|
1155
|
+
if (code !== "23505")
|
|
1156
|
+
continue;
|
|
1157
|
+
if (constraint === "invites_token_hash_unique_idx")
|
|
1158
|
+
return true;
|
|
1159
|
+
if (message.includes("invites_token_hash_unique_idx"))
|
|
1160
|
+
return true;
|
|
1161
|
+
}
|
|
1162
|
+
return false;
|
|
1163
|
+
}
|
|
1164
|
+
function isAbortError(error) {
|
|
1165
|
+
return error instanceof Error && error.name === "AbortError";
|
|
1166
|
+
}
|
|
1167
|
+
async function probeInviteResolutionTarget(url, timeoutMs) {
|
|
1168
|
+
const startedAt = Date.now();
|
|
1169
|
+
const controller = new AbortController();
|
|
1170
|
+
const timeout = setTimeout(() => controller.abort(), timeoutMs);
|
|
1171
|
+
try {
|
|
1172
|
+
const response = await fetch(url, {
|
|
1173
|
+
method: "HEAD",
|
|
1174
|
+
redirect: "manual",
|
|
1175
|
+
signal: controller.signal
|
|
1176
|
+
});
|
|
1177
|
+
const durationMs = Date.now() - startedAt;
|
|
1178
|
+
if (response.ok ||
|
|
1179
|
+
response.status === 401 ||
|
|
1180
|
+
response.status === 403 ||
|
|
1181
|
+
response.status === 404 ||
|
|
1182
|
+
response.status === 405 ||
|
|
1183
|
+
response.status === 422 ||
|
|
1184
|
+
response.status === 500 ||
|
|
1185
|
+
response.status === 501) {
|
|
1186
|
+
return {
|
|
1187
|
+
status: "reachable",
|
|
1188
|
+
method: "HEAD",
|
|
1189
|
+
durationMs,
|
|
1190
|
+
httpStatus: response.status,
|
|
1191
|
+
message: `Webhook endpoint responded to HEAD with HTTP ${response.status}.`
|
|
1192
|
+
};
|
|
1193
|
+
}
|
|
1194
|
+
return {
|
|
1195
|
+
status: "unreachable",
|
|
1196
|
+
method: "HEAD",
|
|
1197
|
+
durationMs,
|
|
1198
|
+
httpStatus: response.status,
|
|
1199
|
+
message: `Webhook endpoint probe returned HTTP ${response.status}.`
|
|
1200
|
+
};
|
|
1201
|
+
}
|
|
1202
|
+
catch (error) {
|
|
1203
|
+
const durationMs = Date.now() - startedAt;
|
|
1204
|
+
if (isAbortError(error)) {
|
|
1205
|
+
return {
|
|
1206
|
+
status: "timeout",
|
|
1207
|
+
method: "HEAD",
|
|
1208
|
+
durationMs,
|
|
1209
|
+
httpStatus: null,
|
|
1210
|
+
message: `Webhook endpoint probe timed out after ${timeoutMs}ms.`
|
|
1211
|
+
};
|
|
1212
|
+
}
|
|
1213
|
+
return {
|
|
1214
|
+
status: "unreachable",
|
|
1215
|
+
method: "HEAD",
|
|
1216
|
+
durationMs,
|
|
1217
|
+
httpStatus: null,
|
|
1218
|
+
message: error instanceof Error
|
|
1219
|
+
? error.message
|
|
1220
|
+
: "Webhook endpoint probe failed."
|
|
1221
|
+
};
|
|
1222
|
+
}
|
|
1223
|
+
finally {
|
|
1224
|
+
clearTimeout(timeout);
|
|
1225
|
+
}
|
|
1226
|
+
}
|
|
1227
|
+
export function accessRoutes(db, opts) {
|
|
1228
|
+
const router = Router();
|
|
1229
|
+
const access = accessService(db);
|
|
1230
|
+
const boardAuth = boardAuthService(db);
|
|
1231
|
+
const agents = agentService(db);
|
|
1232
|
+
async function assertInstanceAdmin(req) {
|
|
1233
|
+
if (req.actor.type !== "board")
|
|
1234
|
+
throw unauthorized();
|
|
1235
|
+
if (isLocalImplicit(req))
|
|
1236
|
+
return;
|
|
1237
|
+
const allowed = await access.isInstanceAdmin(req.actor.userId);
|
|
1238
|
+
if (!allowed)
|
|
1239
|
+
throw forbidden("Instance admin required");
|
|
1240
|
+
}
|
|
1241
|
+
router.get("/board-claim/:token", async (req, res) => {
|
|
1242
|
+
const token = req.params.token.trim();
|
|
1243
|
+
const code = typeof req.query.code === "string" ? req.query.code.trim() : undefined;
|
|
1244
|
+
if (!token)
|
|
1245
|
+
throw notFound("Board claim challenge not found");
|
|
1246
|
+
const challenge = inspectBoardClaimChallenge(token, code);
|
|
1247
|
+
if (challenge.status === "invalid")
|
|
1248
|
+
throw notFound("Board claim challenge not found");
|
|
1249
|
+
res.json(challenge);
|
|
1250
|
+
});
|
|
1251
|
+
router.post("/board-claim/:token/claim", async (req, res) => {
|
|
1252
|
+
const token = req.params.token.trim();
|
|
1253
|
+
const code = typeof req.body?.code === "string" ? req.body.code.trim() : undefined;
|
|
1254
|
+
if (!token)
|
|
1255
|
+
throw notFound("Board claim challenge not found");
|
|
1256
|
+
if (!code)
|
|
1257
|
+
throw badRequest("Claim code is required");
|
|
1258
|
+
if (req.actor.type !== "board" ||
|
|
1259
|
+
req.actor.source !== "session" ||
|
|
1260
|
+
!req.actor.userId) {
|
|
1261
|
+
throw unauthorized("Sign in before claiming board ownership");
|
|
1262
|
+
}
|
|
1263
|
+
const claimed = await claimBoardOwnership(db, {
|
|
1264
|
+
token,
|
|
1265
|
+
code,
|
|
1266
|
+
userId: req.actor.userId
|
|
1267
|
+
});
|
|
1268
|
+
if (claimed.status === "invalid")
|
|
1269
|
+
throw notFound("Board claim challenge not found");
|
|
1270
|
+
if (claimed.status === "expired")
|
|
1271
|
+
throw conflict("Board claim challenge expired. Restart server to generate a new one.");
|
|
1272
|
+
if (claimed.status === "claimed") {
|
|
1273
|
+
res.json({
|
|
1274
|
+
claimed: true,
|
|
1275
|
+
userId: claimed.claimedByUserId ?? req.actor.userId
|
|
1276
|
+
});
|
|
1277
|
+
return;
|
|
1278
|
+
}
|
|
1279
|
+
throw conflict("Board claim challenge is no longer available");
|
|
1280
|
+
});
|
|
1281
|
+
router.post("/cli-auth/challenges", validate(createCliAuthChallengeSchema), async (req, res) => {
|
|
1282
|
+
const created = await boardAuth.createCliAuthChallenge(req.body);
|
|
1283
|
+
const approvalPath = buildCliAuthApprovalPath(created.challenge.id, created.challengeSecret);
|
|
1284
|
+
const baseUrl = requestBaseUrl(req);
|
|
1285
|
+
res.status(201).json({
|
|
1286
|
+
id: created.challenge.id,
|
|
1287
|
+
token: created.challengeSecret,
|
|
1288
|
+
boardApiToken: created.pendingBoardToken,
|
|
1289
|
+
approvalPath,
|
|
1290
|
+
approvalUrl: baseUrl ? `${baseUrl}${approvalPath}` : null,
|
|
1291
|
+
pollPath: `/cli-auth/challenges/${created.challenge.id}`,
|
|
1292
|
+
expiresAt: created.challenge.expiresAt.toISOString(),
|
|
1293
|
+
suggestedPollIntervalMs: 1000,
|
|
1294
|
+
});
|
|
1295
|
+
});
|
|
1296
|
+
router.get("/cli-auth/challenges/:id", async (req, res) => {
|
|
1297
|
+
const id = req.params.id.trim();
|
|
1298
|
+
const token = typeof req.query.token === "string" ? req.query.token.trim() : "";
|
|
1299
|
+
if (!id || !token)
|
|
1300
|
+
throw notFound("CLI auth challenge not found");
|
|
1301
|
+
const challenge = await boardAuth.describeCliAuthChallenge(id, token);
|
|
1302
|
+
if (!challenge)
|
|
1303
|
+
throw notFound("CLI auth challenge not found");
|
|
1304
|
+
const isSignedInBoardUser = req.actor.type === "board" &&
|
|
1305
|
+
(req.actor.source === "session" || isLocalImplicit(req)) &&
|
|
1306
|
+
Boolean(req.actor.userId);
|
|
1307
|
+
const canApprove = isSignedInBoardUser &&
|
|
1308
|
+
(challenge.requestedAccess !== "instance_admin_required" ||
|
|
1309
|
+
isLocalImplicit(req) ||
|
|
1310
|
+
Boolean(req.actor.isInstanceAdmin));
|
|
1311
|
+
res.json({
|
|
1312
|
+
...challenge,
|
|
1313
|
+
requiresSignIn: !isSignedInBoardUser,
|
|
1314
|
+
canApprove,
|
|
1315
|
+
currentUserId: req.actor.type === "board" ? req.actor.userId ?? null : null,
|
|
1316
|
+
});
|
|
1317
|
+
});
|
|
1318
|
+
router.post("/cli-auth/challenges/:id/approve", validate(resolveCliAuthChallengeSchema), async (req, res) => {
|
|
1319
|
+
const id = req.params.id.trim();
|
|
1320
|
+
if (req.actor.type !== "board" ||
|
|
1321
|
+
(!req.actor.userId && !isLocalImplicit(req))) {
|
|
1322
|
+
throw unauthorized("Sign in before approving CLI access");
|
|
1323
|
+
}
|
|
1324
|
+
const userId = req.actor.userId ?? "local-board";
|
|
1325
|
+
const approved = await boardAuth.approveCliAuthChallenge(id, req.body.token, userId);
|
|
1326
|
+
if (approved.status === "approved") {
|
|
1327
|
+
const companyIds = await boardAuth.resolveBoardActivityCompanyIds({
|
|
1328
|
+
userId,
|
|
1329
|
+
requestedCompanyId: approved.challenge.requestedCompanyId,
|
|
1330
|
+
boardApiKeyId: approved.challenge.boardApiKeyId,
|
|
1331
|
+
});
|
|
1332
|
+
for (const companyId of companyIds) {
|
|
1333
|
+
await logActivity(db, {
|
|
1334
|
+
companyId,
|
|
1335
|
+
actorType: "user",
|
|
1336
|
+
actorId: userId,
|
|
1337
|
+
action: "board_api_key.created",
|
|
1338
|
+
entityType: "user",
|
|
1339
|
+
entityId: userId,
|
|
1340
|
+
details: {
|
|
1341
|
+
boardApiKeyId: approved.challenge.boardApiKeyId,
|
|
1342
|
+
requestedAccess: approved.challenge.requestedAccess,
|
|
1343
|
+
requestedCompanyId: approved.challenge.requestedCompanyId,
|
|
1344
|
+
challengeId: approved.challenge.id,
|
|
1345
|
+
},
|
|
1346
|
+
});
|
|
1347
|
+
}
|
|
1348
|
+
}
|
|
1349
|
+
res.json({
|
|
1350
|
+
approved: approved.status === "approved",
|
|
1351
|
+
status: approved.status,
|
|
1352
|
+
userId,
|
|
1353
|
+
keyId: approved.challenge.boardApiKeyId ?? null,
|
|
1354
|
+
expiresAt: approved.challenge.expiresAt.toISOString(),
|
|
1355
|
+
});
|
|
1356
|
+
});
|
|
1357
|
+
router.post("/cli-auth/challenges/:id/cancel", validate(resolveCliAuthChallengeSchema), async (req, res) => {
|
|
1358
|
+
const id = req.params.id.trim();
|
|
1359
|
+
const cancelled = await boardAuth.cancelCliAuthChallenge(id, req.body.token);
|
|
1360
|
+
res.json({
|
|
1361
|
+
status: cancelled.status,
|
|
1362
|
+
cancelled: cancelled.status === "cancelled",
|
|
1363
|
+
});
|
|
1364
|
+
});
|
|
1365
|
+
router.get("/cli-auth/me", async (req, res) => {
|
|
1366
|
+
if (req.actor.type !== "board" || !req.actor.userId) {
|
|
1367
|
+
throw unauthorized("Board authentication required");
|
|
1368
|
+
}
|
|
1369
|
+
const accessSnapshot = await boardAuth.resolveBoardAccess(req.actor.userId);
|
|
1370
|
+
res.json({
|
|
1371
|
+
user: accessSnapshot.user,
|
|
1372
|
+
userId: req.actor.userId,
|
|
1373
|
+
isInstanceAdmin: accessSnapshot.isInstanceAdmin,
|
|
1374
|
+
companyIds: accessSnapshot.companyIds,
|
|
1375
|
+
source: req.actor.source ?? "none",
|
|
1376
|
+
keyId: req.actor.source === "board_key" ? req.actor.keyId ?? null : null,
|
|
1377
|
+
});
|
|
1378
|
+
});
|
|
1379
|
+
router.post("/cli-auth/revoke-current", async (req, res) => {
|
|
1380
|
+
if (req.actor.type !== "board" || req.actor.source !== "board_key") {
|
|
1381
|
+
throw badRequest("Current board API key context is required");
|
|
1382
|
+
}
|
|
1383
|
+
const key = await boardAuth.assertCurrentBoardKey(req.actor.keyId, req.actor.userId);
|
|
1384
|
+
await boardAuth.revokeBoardApiKey(key.id);
|
|
1385
|
+
const companyIds = await boardAuth.resolveBoardActivityCompanyIds({
|
|
1386
|
+
userId: key.userId,
|
|
1387
|
+
boardApiKeyId: key.id,
|
|
1388
|
+
});
|
|
1389
|
+
for (const companyId of companyIds) {
|
|
1390
|
+
await logActivity(db, {
|
|
1391
|
+
companyId,
|
|
1392
|
+
actorType: "user",
|
|
1393
|
+
actorId: key.userId,
|
|
1394
|
+
action: "board_api_key.revoked",
|
|
1395
|
+
entityType: "user",
|
|
1396
|
+
entityId: key.userId,
|
|
1397
|
+
details: {
|
|
1398
|
+
boardApiKeyId: key.id,
|
|
1399
|
+
revokedVia: "cli_auth_logout",
|
|
1400
|
+
},
|
|
1401
|
+
});
|
|
1402
|
+
}
|
|
1403
|
+
res.json({ revoked: true, keyId: key.id });
|
|
1404
|
+
});
|
|
1405
|
+
async function assertCompanyPermission(req, companyId, permissionKey) {
|
|
1406
|
+
assertCompanyAccess(req, companyId);
|
|
1407
|
+
if (req.actor.type === "agent") {
|
|
1408
|
+
if (!req.actor.agentId)
|
|
1409
|
+
throw forbidden();
|
|
1410
|
+
const allowed = await access.hasPermission(companyId, "agent", req.actor.agentId, permissionKey);
|
|
1411
|
+
if (!allowed)
|
|
1412
|
+
throw forbidden("Permission denied");
|
|
1413
|
+
return;
|
|
1414
|
+
}
|
|
1415
|
+
if (req.actor.type !== "board")
|
|
1416
|
+
throw unauthorized();
|
|
1417
|
+
if (isLocalImplicit(req))
|
|
1418
|
+
return;
|
|
1419
|
+
const allowed = await access.canUser(companyId, req.actor.userId, permissionKey);
|
|
1420
|
+
if (!allowed)
|
|
1421
|
+
throw forbidden("Permission denied");
|
|
1422
|
+
}
|
|
1423
|
+
async function assertCanGenerateOpenClawInvitePrompt(req, companyId) {
|
|
1424
|
+
assertCompanyAccess(req, companyId);
|
|
1425
|
+
if (req.actor.type === "agent") {
|
|
1426
|
+
if (!req.actor.agentId)
|
|
1427
|
+
throw forbidden("Agent authentication required");
|
|
1428
|
+
const actorAgent = await agents.getById(req.actor.agentId);
|
|
1429
|
+
if (!actorAgent || actorAgent.companyId !== companyId) {
|
|
1430
|
+
throw forbidden("Agent key cannot access another company");
|
|
1431
|
+
}
|
|
1432
|
+
if (actorAgent.role !== "ceo") {
|
|
1433
|
+
throw forbidden("Only CEO agents can generate OpenClaw invite prompts");
|
|
1434
|
+
}
|
|
1435
|
+
return;
|
|
1436
|
+
}
|
|
1437
|
+
if (req.actor.type !== "board")
|
|
1438
|
+
throw unauthorized();
|
|
1439
|
+
if (isLocalImplicit(req))
|
|
1440
|
+
return;
|
|
1441
|
+
const allowed = await access.canUser(companyId, req.actor.userId, "users:invite");
|
|
1442
|
+
if (!allowed)
|
|
1443
|
+
throw forbidden("Permission denied");
|
|
1444
|
+
}
|
|
1445
|
+
async function createCompanyInviteForCompany(input) {
|
|
1446
|
+
const normalizedAgentMessage = typeof input.agentMessage === "string"
|
|
1447
|
+
? input.agentMessage.trim() || null
|
|
1448
|
+
: null;
|
|
1449
|
+
const insertValues = {
|
|
1450
|
+
companyId: input.companyId,
|
|
1451
|
+
inviteType: "company_join",
|
|
1452
|
+
allowedJoinTypes: input.allowedJoinTypes,
|
|
1453
|
+
defaultsPayload: mergeInviteDefaults(input.defaultsPayload ?? null, normalizedAgentMessage),
|
|
1454
|
+
expiresAt: companyInviteExpiresAt(),
|
|
1455
|
+
invitedByUserId: input.req.actor.userId ?? null
|
|
1456
|
+
};
|
|
1457
|
+
let token = null;
|
|
1458
|
+
let created = null;
|
|
1459
|
+
for (let attempt = 0; attempt < INVITE_TOKEN_MAX_RETRIES; attempt += 1) {
|
|
1460
|
+
const candidateToken = createInviteToken();
|
|
1461
|
+
try {
|
|
1462
|
+
const row = await db
|
|
1463
|
+
.insert(invites)
|
|
1464
|
+
.values({
|
|
1465
|
+
...insertValues,
|
|
1466
|
+
tokenHash: hashToken(candidateToken)
|
|
1467
|
+
})
|
|
1468
|
+
.returning()
|
|
1469
|
+
.then((rows) => rows[0]);
|
|
1470
|
+
token = candidateToken;
|
|
1471
|
+
created = row;
|
|
1472
|
+
break;
|
|
1473
|
+
}
|
|
1474
|
+
catch (error) {
|
|
1475
|
+
if (!isInviteTokenHashCollisionError(error)) {
|
|
1476
|
+
throw error;
|
|
1477
|
+
}
|
|
1478
|
+
}
|
|
1479
|
+
}
|
|
1480
|
+
if (!token || !created) {
|
|
1481
|
+
throw conflict("Failed to generate a unique invite token. Please retry.");
|
|
1482
|
+
}
|
|
1483
|
+
return { token, created, normalizedAgentMessage };
|
|
1484
|
+
}
|
|
1485
|
+
router.get("/skills/available", (_req, res) => {
|
|
1486
|
+
res.json({ skills: listAvailableSkills() });
|
|
1487
|
+
});
|
|
1488
|
+
router.get("/skills/index", (_req, res) => {
|
|
1489
|
+
res.json({
|
|
1490
|
+
skills: [
|
|
1491
|
+
{ name: "fidelios", path: "/api/skills/fidelios" },
|
|
1492
|
+
{
|
|
1493
|
+
name: "para-memory-files",
|
|
1494
|
+
path: "/api/skills/para-memory-files"
|
|
1495
|
+
},
|
|
1496
|
+
{
|
|
1497
|
+
name: "fidelios-create-agent",
|
|
1498
|
+
path: "/api/skills/fidelios-create-agent"
|
|
1499
|
+
}
|
|
1500
|
+
]
|
|
1501
|
+
});
|
|
1502
|
+
});
|
|
1503
|
+
router.get("/skills/:skillName", (req, res) => {
|
|
1504
|
+
const skillName = req.params.skillName.trim().toLowerCase();
|
|
1505
|
+
const markdown = readSkillMarkdown(skillName);
|
|
1506
|
+
if (!markdown)
|
|
1507
|
+
throw notFound("Skill not found");
|
|
1508
|
+
res.type("text/markdown").send(markdown);
|
|
1509
|
+
});
|
|
1510
|
+
router.post("/companies/:companyId/invites", validate(createCompanyInviteSchema), async (req, res) => {
|
|
1511
|
+
const companyId = req.params.companyId;
|
|
1512
|
+
await assertCompanyPermission(req, companyId, "users:invite");
|
|
1513
|
+
const { token, created, normalizedAgentMessage } = await createCompanyInviteForCompany({
|
|
1514
|
+
req,
|
|
1515
|
+
companyId,
|
|
1516
|
+
allowedJoinTypes: req.body.allowedJoinTypes,
|
|
1517
|
+
defaultsPayload: req.body.defaultsPayload ?? null,
|
|
1518
|
+
agentMessage: req.body.agentMessage ?? null
|
|
1519
|
+
});
|
|
1520
|
+
await logActivity(db, {
|
|
1521
|
+
companyId,
|
|
1522
|
+
actorType: req.actor.type === "agent" ? "agent" : "user",
|
|
1523
|
+
actorId: req.actor.type === "agent"
|
|
1524
|
+
? req.actor.agentId ?? "unknown-agent"
|
|
1525
|
+
: req.actor.userId ?? "board",
|
|
1526
|
+
action: "invite.created",
|
|
1527
|
+
entityType: "invite",
|
|
1528
|
+
entityId: created.id,
|
|
1529
|
+
details: {
|
|
1530
|
+
inviteType: created.inviteType,
|
|
1531
|
+
allowedJoinTypes: created.allowedJoinTypes,
|
|
1532
|
+
expiresAt: created.expiresAt.toISOString(),
|
|
1533
|
+
hasAgentMessage: Boolean(normalizedAgentMessage)
|
|
1534
|
+
}
|
|
1535
|
+
});
|
|
1536
|
+
const inviteSummary = toInviteSummaryResponse(req, token, created);
|
|
1537
|
+
res.status(201).json({
|
|
1538
|
+
...created,
|
|
1539
|
+
token,
|
|
1540
|
+
inviteUrl: `/invite/${token}`,
|
|
1541
|
+
onboardingTextPath: inviteSummary.onboardingTextPath,
|
|
1542
|
+
onboardingTextUrl: inviteSummary.onboardingTextUrl,
|
|
1543
|
+
inviteMessage: inviteSummary.inviteMessage
|
|
1544
|
+
});
|
|
1545
|
+
});
|
|
1546
|
+
router.post("/companies/:companyId/openclaw/invite-prompt", validate(createOpenClawInvitePromptSchema), async (req, res) => {
|
|
1547
|
+
const companyId = req.params.companyId;
|
|
1548
|
+
await assertCanGenerateOpenClawInvitePrompt(req, companyId);
|
|
1549
|
+
const { token, created, normalizedAgentMessage } = await createCompanyInviteForCompany({
|
|
1550
|
+
req,
|
|
1551
|
+
companyId,
|
|
1552
|
+
allowedJoinTypes: "agent",
|
|
1553
|
+
defaultsPayload: null,
|
|
1554
|
+
agentMessage: req.body.agentMessage ?? null
|
|
1555
|
+
});
|
|
1556
|
+
await logActivity(db, {
|
|
1557
|
+
companyId,
|
|
1558
|
+
actorType: req.actor.type === "agent" ? "agent" : "user",
|
|
1559
|
+
actorId: req.actor.type === "agent"
|
|
1560
|
+
? req.actor.agentId ?? "unknown-agent"
|
|
1561
|
+
: req.actor.userId ?? "board",
|
|
1562
|
+
action: "invite.openclaw_prompt_created",
|
|
1563
|
+
entityType: "invite",
|
|
1564
|
+
entityId: created.id,
|
|
1565
|
+
details: {
|
|
1566
|
+
inviteType: created.inviteType,
|
|
1567
|
+
allowedJoinTypes: created.allowedJoinTypes,
|
|
1568
|
+
expiresAt: created.expiresAt.toISOString(),
|
|
1569
|
+
hasAgentMessage: Boolean(normalizedAgentMessage)
|
|
1570
|
+
}
|
|
1571
|
+
});
|
|
1572
|
+
const inviteSummary = toInviteSummaryResponse(req, token, created);
|
|
1573
|
+
res.status(201).json({
|
|
1574
|
+
...created,
|
|
1575
|
+
token,
|
|
1576
|
+
inviteUrl: `/invite/${token}`,
|
|
1577
|
+
onboardingTextPath: inviteSummary.onboardingTextPath,
|
|
1578
|
+
onboardingTextUrl: inviteSummary.onboardingTextUrl,
|
|
1579
|
+
inviteMessage: inviteSummary.inviteMessage
|
|
1580
|
+
});
|
|
1581
|
+
});
|
|
1582
|
+
router.get("/invites/:token", async (req, res) => {
|
|
1583
|
+
const token = req.params.token.trim();
|
|
1584
|
+
if (!token)
|
|
1585
|
+
throw notFound("Invite not found");
|
|
1586
|
+
const invite = await db
|
|
1587
|
+
.select()
|
|
1588
|
+
.from(invites)
|
|
1589
|
+
.where(eq(invites.tokenHash, hashToken(token)))
|
|
1590
|
+
.then((rows) => rows[0] ?? null);
|
|
1591
|
+
if (!invite ||
|
|
1592
|
+
invite.revokedAt ||
|
|
1593
|
+
invite.acceptedAt ||
|
|
1594
|
+
inviteExpired(invite)) {
|
|
1595
|
+
throw notFound("Invite not found");
|
|
1596
|
+
}
|
|
1597
|
+
res.json(toInviteSummaryResponse(req, token, invite));
|
|
1598
|
+
});
|
|
1599
|
+
router.get("/invites/:token/onboarding", async (req, res) => {
|
|
1600
|
+
const token = req.params.token.trim();
|
|
1601
|
+
if (!token)
|
|
1602
|
+
throw notFound("Invite not found");
|
|
1603
|
+
const invite = await db
|
|
1604
|
+
.select()
|
|
1605
|
+
.from(invites)
|
|
1606
|
+
.where(eq(invites.tokenHash, hashToken(token)))
|
|
1607
|
+
.then((rows) => rows[0] ?? null);
|
|
1608
|
+
if (!invite || invite.revokedAt || inviteExpired(invite)) {
|
|
1609
|
+
throw notFound("Invite not found");
|
|
1610
|
+
}
|
|
1611
|
+
res.json(buildInviteOnboardingManifest(req, token, invite, opts));
|
|
1612
|
+
});
|
|
1613
|
+
router.get("/invites/:token/onboarding.txt", async (req, res) => {
|
|
1614
|
+
const token = req.params.token.trim();
|
|
1615
|
+
if (!token)
|
|
1616
|
+
throw notFound("Invite not found");
|
|
1617
|
+
const invite = await db
|
|
1618
|
+
.select()
|
|
1619
|
+
.from(invites)
|
|
1620
|
+
.where(eq(invites.tokenHash, hashToken(token)))
|
|
1621
|
+
.then((rows) => rows[0] ?? null);
|
|
1622
|
+
if (!invite || invite.revokedAt || inviteExpired(invite)) {
|
|
1623
|
+
throw notFound("Invite not found");
|
|
1624
|
+
}
|
|
1625
|
+
res
|
|
1626
|
+
.type("text/plain; charset=utf-8")
|
|
1627
|
+
.send(buildInviteOnboardingTextDocument(req, token, invite, opts));
|
|
1628
|
+
});
|
|
1629
|
+
router.get("/invites/:token/test-resolution", async (req, res) => {
|
|
1630
|
+
const token = req.params.token.trim();
|
|
1631
|
+
if (!token)
|
|
1632
|
+
throw notFound("Invite not found");
|
|
1633
|
+
const invite = await db
|
|
1634
|
+
.select()
|
|
1635
|
+
.from(invites)
|
|
1636
|
+
.where(eq(invites.tokenHash, hashToken(token)))
|
|
1637
|
+
.then((rows) => rows[0] ?? null);
|
|
1638
|
+
if (!invite || invite.revokedAt || inviteExpired(invite)) {
|
|
1639
|
+
throw notFound("Invite not found");
|
|
1640
|
+
}
|
|
1641
|
+
const rawUrl = typeof req.query.url === "string" ? req.query.url.trim() : "";
|
|
1642
|
+
if (!rawUrl)
|
|
1643
|
+
throw badRequest("url query parameter is required");
|
|
1644
|
+
let target;
|
|
1645
|
+
try {
|
|
1646
|
+
target = new URL(rawUrl);
|
|
1647
|
+
}
|
|
1648
|
+
catch {
|
|
1649
|
+
throw badRequest("url must be an absolute http(s) URL");
|
|
1650
|
+
}
|
|
1651
|
+
if (target.protocol !== "http:" && target.protocol !== "https:") {
|
|
1652
|
+
throw badRequest("url must use http or https");
|
|
1653
|
+
}
|
|
1654
|
+
const parsedTimeoutMs = typeof req.query.timeoutMs === "string"
|
|
1655
|
+
? Number(req.query.timeoutMs)
|
|
1656
|
+
: NaN;
|
|
1657
|
+
const timeoutMs = Number.isFinite(parsedTimeoutMs)
|
|
1658
|
+
? Math.max(1000, Math.min(15000, Math.floor(parsedTimeoutMs)))
|
|
1659
|
+
: 5000;
|
|
1660
|
+
const probe = await probeInviteResolutionTarget(target, timeoutMs);
|
|
1661
|
+
res.json({
|
|
1662
|
+
inviteId: invite.id,
|
|
1663
|
+
testResolutionPath: `/api/invites/${token}/test-resolution`,
|
|
1664
|
+
requestedUrl: target.toString(),
|
|
1665
|
+
timeoutMs,
|
|
1666
|
+
...probe
|
|
1667
|
+
});
|
|
1668
|
+
});
|
|
1669
|
+
router.post("/invites/:token/accept", validate(acceptInviteSchema), async (req, res) => {
|
|
1670
|
+
const token = req.params.token.trim();
|
|
1671
|
+
if (!token)
|
|
1672
|
+
throw notFound("Invite not found");
|
|
1673
|
+
const invite = await db
|
|
1674
|
+
.select()
|
|
1675
|
+
.from(invites)
|
|
1676
|
+
.where(eq(invites.tokenHash, hashToken(token)))
|
|
1677
|
+
.then((rows) => rows[0] ?? null);
|
|
1678
|
+
if (!invite || invite.revokedAt || inviteExpired(invite)) {
|
|
1679
|
+
throw notFound("Invite not found");
|
|
1680
|
+
}
|
|
1681
|
+
const inviteAlreadyAccepted = Boolean(invite.acceptedAt);
|
|
1682
|
+
const existingJoinRequestForInvite = inviteAlreadyAccepted
|
|
1683
|
+
? await db
|
|
1684
|
+
.select()
|
|
1685
|
+
.from(joinRequests)
|
|
1686
|
+
.where(eq(joinRequests.inviteId, invite.id))
|
|
1687
|
+
.then((rows) => rows[0] ?? null)
|
|
1688
|
+
: null;
|
|
1689
|
+
if (invite.inviteType === "bootstrap_ceo") {
|
|
1690
|
+
if (inviteAlreadyAccepted)
|
|
1691
|
+
throw notFound("Invite not found");
|
|
1692
|
+
if (req.body.requestType !== "human") {
|
|
1693
|
+
throw badRequest("Bootstrap invite requires human request type");
|
|
1694
|
+
}
|
|
1695
|
+
if (req.actor.type !== "board" ||
|
|
1696
|
+
(!req.actor.userId && !isLocalImplicit(req))) {
|
|
1697
|
+
throw unauthorized("Authenticated user required for bootstrap acceptance");
|
|
1698
|
+
}
|
|
1699
|
+
const userId = req.actor.userId ?? "local-board";
|
|
1700
|
+
const existingAdmin = await access.isInstanceAdmin(userId);
|
|
1701
|
+
if (!existingAdmin) {
|
|
1702
|
+
await access.promoteInstanceAdmin(userId);
|
|
1703
|
+
}
|
|
1704
|
+
const updatedInvite = await db
|
|
1705
|
+
.update(invites)
|
|
1706
|
+
.set({ acceptedAt: new Date(), updatedAt: new Date() })
|
|
1707
|
+
.where(eq(invites.id, invite.id))
|
|
1708
|
+
.returning()
|
|
1709
|
+
.then((rows) => rows[0] ?? invite);
|
|
1710
|
+
res.status(202).json({
|
|
1711
|
+
inviteId: updatedInvite.id,
|
|
1712
|
+
inviteType: updatedInvite.inviteType,
|
|
1713
|
+
bootstrapAccepted: true,
|
|
1714
|
+
userId
|
|
1715
|
+
});
|
|
1716
|
+
return;
|
|
1717
|
+
}
|
|
1718
|
+
const requestType = req.body.requestType;
|
|
1719
|
+
const companyId = invite.companyId;
|
|
1720
|
+
if (!companyId)
|
|
1721
|
+
throw conflict("Invite is missing company scope");
|
|
1722
|
+
if (invite.allowedJoinTypes !== "both" &&
|
|
1723
|
+
invite.allowedJoinTypes !== requestType) {
|
|
1724
|
+
throw badRequest(`Invite does not allow ${requestType} joins`);
|
|
1725
|
+
}
|
|
1726
|
+
if (requestType === "human" && req.actor.type !== "board") {
|
|
1727
|
+
throw unauthorized("Human invite acceptance requires authenticated user");
|
|
1728
|
+
}
|
|
1729
|
+
if (requestType === "human" &&
|
|
1730
|
+
!req.actor.userId &&
|
|
1731
|
+
!isLocalImplicit(req)) {
|
|
1732
|
+
throw unauthorized("Authenticated user is required");
|
|
1733
|
+
}
|
|
1734
|
+
if (requestType === "agent" && !req.body.agentName) {
|
|
1735
|
+
if (!inviteAlreadyAccepted ||
|
|
1736
|
+
!existingJoinRequestForInvite?.agentName) {
|
|
1737
|
+
throw badRequest("agentName is required for agent join requests");
|
|
1738
|
+
}
|
|
1739
|
+
}
|
|
1740
|
+
const adapterType = req.body.adapterType ?? null;
|
|
1741
|
+
if (inviteAlreadyAccepted &&
|
|
1742
|
+
!canReplayOpenClawGatewayInviteAccept({
|
|
1743
|
+
requestType,
|
|
1744
|
+
adapterType,
|
|
1745
|
+
existingJoinRequest: existingJoinRequestForInvite
|
|
1746
|
+
})) {
|
|
1747
|
+
throw notFound("Invite not found");
|
|
1748
|
+
}
|
|
1749
|
+
const replayJoinRequestId = inviteAlreadyAccepted
|
|
1750
|
+
? existingJoinRequestForInvite?.id ?? null
|
|
1751
|
+
: null;
|
|
1752
|
+
if (inviteAlreadyAccepted && !replayJoinRequestId) {
|
|
1753
|
+
throw conflict("Join request not found");
|
|
1754
|
+
}
|
|
1755
|
+
const replayMergedDefaults = inviteAlreadyAccepted
|
|
1756
|
+
? mergeJoinDefaultsPayloadForReplay(existingJoinRequestForInvite?.agentDefaultsPayload ?? null, req.body.agentDefaultsPayload ?? null)
|
|
1757
|
+
: req.body.agentDefaultsPayload ?? null;
|
|
1758
|
+
const gatewayDefaultsPayload = requestType === "agent"
|
|
1759
|
+
? buildJoinDefaultsPayloadForAccept({
|
|
1760
|
+
adapterType,
|
|
1761
|
+
defaultsPayload: replayMergedDefaults,
|
|
1762
|
+
fideliosApiUrl: req.body.fideliosApiUrl ?? null,
|
|
1763
|
+
inboundOpenClawAuthHeader: req.header("x-openclaw-auth") ?? null,
|
|
1764
|
+
inboundOpenClawTokenHeader: req.header("x-openclaw-token") ?? null
|
|
1765
|
+
})
|
|
1766
|
+
: null;
|
|
1767
|
+
const joinDefaults = requestType === "agent"
|
|
1768
|
+
? normalizeAgentDefaultsForJoin({
|
|
1769
|
+
adapterType,
|
|
1770
|
+
defaultsPayload: gatewayDefaultsPayload,
|
|
1771
|
+
deploymentMode: opts.deploymentMode,
|
|
1772
|
+
deploymentExposure: opts.deploymentExposure,
|
|
1773
|
+
bindHost: opts.bindHost,
|
|
1774
|
+
allowedHostnames: opts.allowedHostnames
|
|
1775
|
+
})
|
|
1776
|
+
: {
|
|
1777
|
+
normalized: null,
|
|
1778
|
+
diagnostics: [],
|
|
1779
|
+
fatalErrors: []
|
|
1780
|
+
};
|
|
1781
|
+
if (requestType === "agent" && joinDefaults.fatalErrors.length > 0) {
|
|
1782
|
+
throw badRequest(joinDefaults.fatalErrors.join("; "));
|
|
1783
|
+
}
|
|
1784
|
+
if (requestType === "agent" && adapterType === "openclaw_gateway") {
|
|
1785
|
+
logger.info({
|
|
1786
|
+
inviteId: invite.id,
|
|
1787
|
+
joinRequestDiagnostics: joinDefaults.diagnostics.map((diag) => ({
|
|
1788
|
+
code: diag.code,
|
|
1789
|
+
level: diag.level
|
|
1790
|
+
})),
|
|
1791
|
+
normalizedAgentDefaults: summarizeOpenClawGatewayDefaultsForLog(joinDefaults.normalized)
|
|
1792
|
+
}, "invite accept normalized OpenClaw gateway defaults");
|
|
1793
|
+
}
|
|
1794
|
+
const claimSecret = requestType === "agent" && !inviteAlreadyAccepted
|
|
1795
|
+
? createClaimSecret()
|
|
1796
|
+
: null;
|
|
1797
|
+
const claimSecretHash = claimSecret ? hashToken(claimSecret) : null;
|
|
1798
|
+
const claimSecretExpiresAt = claimSecret
|
|
1799
|
+
? new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
|
|
1800
|
+
: null;
|
|
1801
|
+
const actorEmail = requestType === "human" ? await resolveActorEmail(db, req) : null;
|
|
1802
|
+
const created = !inviteAlreadyAccepted
|
|
1803
|
+
? await db.transaction(async (tx) => {
|
|
1804
|
+
await tx
|
|
1805
|
+
.update(invites)
|
|
1806
|
+
.set({ acceptedAt: new Date(), updatedAt: new Date() })
|
|
1807
|
+
.where(and(eq(invites.id, invite.id), isNull(invites.acceptedAt), isNull(invites.revokedAt)));
|
|
1808
|
+
const row = await tx
|
|
1809
|
+
.insert(joinRequests)
|
|
1810
|
+
.values({
|
|
1811
|
+
inviteId: invite.id,
|
|
1812
|
+
companyId,
|
|
1813
|
+
requestType,
|
|
1814
|
+
status: "pending_approval",
|
|
1815
|
+
requestIp: requestIp(req),
|
|
1816
|
+
requestingUserId: requestType === "human"
|
|
1817
|
+
? req.actor.userId ?? "local-board"
|
|
1818
|
+
: null,
|
|
1819
|
+
requestEmailSnapshot: requestType === "human" ? actorEmail : null,
|
|
1820
|
+
agentName: requestType === "agent" ? req.body.agentName : null,
|
|
1821
|
+
adapterType: requestType === "agent" ? adapterType : null,
|
|
1822
|
+
capabilities: requestType === "agent"
|
|
1823
|
+
? req.body.capabilities ?? null
|
|
1824
|
+
: null,
|
|
1825
|
+
agentDefaultsPayload: requestType === "agent" ? joinDefaults.normalized : null,
|
|
1826
|
+
claimSecretHash,
|
|
1827
|
+
claimSecretExpiresAt
|
|
1828
|
+
})
|
|
1829
|
+
.returning()
|
|
1830
|
+
.then((rows) => rows[0]);
|
|
1831
|
+
return row;
|
|
1832
|
+
})
|
|
1833
|
+
: await db
|
|
1834
|
+
.update(joinRequests)
|
|
1835
|
+
.set({
|
|
1836
|
+
requestIp: requestIp(req),
|
|
1837
|
+
agentName: requestType === "agent"
|
|
1838
|
+
? req.body.agentName ??
|
|
1839
|
+
existingJoinRequestForInvite?.agentName ??
|
|
1840
|
+
null
|
|
1841
|
+
: null,
|
|
1842
|
+
capabilities: requestType === "agent"
|
|
1843
|
+
? req.body.capabilities ??
|
|
1844
|
+
existingJoinRequestForInvite?.capabilities ??
|
|
1845
|
+
null
|
|
1846
|
+
: null,
|
|
1847
|
+
adapterType: requestType === "agent" ? adapterType : null,
|
|
1848
|
+
agentDefaultsPayload: requestType === "agent" ? joinDefaults.normalized : null,
|
|
1849
|
+
updatedAt: new Date()
|
|
1850
|
+
})
|
|
1851
|
+
.where(eq(joinRequests.id, replayJoinRequestId))
|
|
1852
|
+
.returning()
|
|
1853
|
+
.then((rows) => rows[0]);
|
|
1854
|
+
if (!created) {
|
|
1855
|
+
throw conflict("Join request not found");
|
|
1856
|
+
}
|
|
1857
|
+
if (inviteAlreadyAccepted &&
|
|
1858
|
+
requestType === "agent" &&
|
|
1859
|
+
adapterType === "openclaw_gateway" &&
|
|
1860
|
+
created.status === "approved" &&
|
|
1861
|
+
created.createdAgentId) {
|
|
1862
|
+
const existingAgent = await agents.getById(created.createdAgentId);
|
|
1863
|
+
if (!existingAgent) {
|
|
1864
|
+
throw conflict("Approved join request agent not found");
|
|
1865
|
+
}
|
|
1866
|
+
const existingAdapterConfig = isPlainObject(existingAgent.adapterConfig)
|
|
1867
|
+
? existingAgent.adapterConfig
|
|
1868
|
+
: {};
|
|
1869
|
+
const nextAdapterConfig = {
|
|
1870
|
+
...existingAdapterConfig,
|
|
1871
|
+
...(joinDefaults.normalized ?? {})
|
|
1872
|
+
};
|
|
1873
|
+
const updatedAgent = await agents.update(created.createdAgentId, {
|
|
1874
|
+
adapterType,
|
|
1875
|
+
adapterConfig: nextAdapterConfig
|
|
1876
|
+
});
|
|
1877
|
+
if (!updatedAgent) {
|
|
1878
|
+
throw conflict("Approved join request agent not found");
|
|
1879
|
+
}
|
|
1880
|
+
await logActivity(db, {
|
|
1881
|
+
companyId,
|
|
1882
|
+
actorType: req.actor.type === "agent" ? "agent" : "user",
|
|
1883
|
+
actorId: req.actor.type === "agent"
|
|
1884
|
+
? req.actor.agentId ?? "invite-agent"
|
|
1885
|
+
: req.actor.userId ?? "board",
|
|
1886
|
+
action: "agent.updated_from_join_replay",
|
|
1887
|
+
entityType: "agent",
|
|
1888
|
+
entityId: updatedAgent.id,
|
|
1889
|
+
details: { inviteId: invite.id, joinRequestId: created.id }
|
|
1890
|
+
});
|
|
1891
|
+
}
|
|
1892
|
+
if (requestType === "agent" && adapterType === "openclaw_gateway") {
|
|
1893
|
+
const expectedDefaults = summarizeOpenClawGatewayDefaultsForLog(joinDefaults.normalized);
|
|
1894
|
+
const persistedDefaults = summarizeOpenClawGatewayDefaultsForLog(created.agentDefaultsPayload);
|
|
1895
|
+
const missingPersistedFields = [];
|
|
1896
|
+
if (expectedDefaults.url && !persistedDefaults.url)
|
|
1897
|
+
missingPersistedFields.push("url");
|
|
1898
|
+
if (expectedDefaults.fideliosApiUrl &&
|
|
1899
|
+
!persistedDefaults.fideliosApiUrl) {
|
|
1900
|
+
missingPersistedFields.push("fideliosApiUrl");
|
|
1901
|
+
}
|
|
1902
|
+
if (expectedDefaults.gatewayToken && !persistedDefaults.gatewayToken) {
|
|
1903
|
+
missingPersistedFields.push("headers.x-openclaw-token");
|
|
1904
|
+
}
|
|
1905
|
+
if (expectedDefaults.devicePrivateKeyPem &&
|
|
1906
|
+
!persistedDefaults.devicePrivateKeyPem) {
|
|
1907
|
+
missingPersistedFields.push("devicePrivateKeyPem");
|
|
1908
|
+
}
|
|
1909
|
+
if (expectedDefaults.headerKeys.length > 0 &&
|
|
1910
|
+
persistedDefaults.headerKeys.length === 0) {
|
|
1911
|
+
missingPersistedFields.push("headers");
|
|
1912
|
+
}
|
|
1913
|
+
logger.info({
|
|
1914
|
+
inviteId: invite.id,
|
|
1915
|
+
joinRequestId: created.id,
|
|
1916
|
+
joinRequestStatus: created.status,
|
|
1917
|
+
expectedDefaults,
|
|
1918
|
+
persistedDefaults,
|
|
1919
|
+
diagnostics: joinDefaults.diagnostics.map((diag) => ({
|
|
1920
|
+
code: diag.code,
|
|
1921
|
+
level: diag.level,
|
|
1922
|
+
message: diag.message,
|
|
1923
|
+
hint: diag.hint ?? null
|
|
1924
|
+
}))
|
|
1925
|
+
}, "invite accept persisted OpenClaw gateway join request");
|
|
1926
|
+
if (missingPersistedFields.length > 0) {
|
|
1927
|
+
logger.warn({
|
|
1928
|
+
inviteId: invite.id,
|
|
1929
|
+
joinRequestId: created.id,
|
|
1930
|
+
missingPersistedFields
|
|
1931
|
+
}, "invite accept detected missing persisted OpenClaw gateway defaults");
|
|
1932
|
+
}
|
|
1933
|
+
}
|
|
1934
|
+
await logActivity(db, {
|
|
1935
|
+
companyId,
|
|
1936
|
+
actorType: req.actor.type === "agent" ? "agent" : "user",
|
|
1937
|
+
actorId: req.actor.type === "agent"
|
|
1938
|
+
? req.actor.agentId ?? "invite-agent"
|
|
1939
|
+
: req.actor.userId ??
|
|
1940
|
+
(requestType === "agent" ? "invite-anon" : "board"),
|
|
1941
|
+
action: inviteAlreadyAccepted
|
|
1942
|
+
? "join.request_replayed"
|
|
1943
|
+
: "join.requested",
|
|
1944
|
+
entityType: "join_request",
|
|
1945
|
+
entityId: created.id,
|
|
1946
|
+
details: {
|
|
1947
|
+
requestType,
|
|
1948
|
+
requestIp: created.requestIp,
|
|
1949
|
+
inviteReplay: inviteAlreadyAccepted
|
|
1950
|
+
}
|
|
1951
|
+
});
|
|
1952
|
+
const response = toJoinRequestResponse(created);
|
|
1953
|
+
if (claimSecret) {
|
|
1954
|
+
const onboardingManifest = buildInviteOnboardingManifest(req, token, invite, opts);
|
|
1955
|
+
res.status(202).json({
|
|
1956
|
+
...response,
|
|
1957
|
+
claimSecret,
|
|
1958
|
+
claimApiKeyPath: `/api/join-requests/${created.id}/claim-api-key`,
|
|
1959
|
+
onboarding: onboardingManifest.onboarding,
|
|
1960
|
+
diagnostics: joinDefaults.diagnostics
|
|
1961
|
+
});
|
|
1962
|
+
return;
|
|
1963
|
+
}
|
|
1964
|
+
res.status(202).json({
|
|
1965
|
+
...response,
|
|
1966
|
+
...(joinDefaults.diagnostics.length > 0
|
|
1967
|
+
? { diagnostics: joinDefaults.diagnostics }
|
|
1968
|
+
: {})
|
|
1969
|
+
});
|
|
1970
|
+
});
|
|
1971
|
+
router.post("/invites/:inviteId/revoke", async (req, res) => {
|
|
1972
|
+
const id = req.params.inviteId;
|
|
1973
|
+
const invite = await db
|
|
1974
|
+
.select()
|
|
1975
|
+
.from(invites)
|
|
1976
|
+
.where(eq(invites.id, id))
|
|
1977
|
+
.then((rows) => rows[0] ?? null);
|
|
1978
|
+
if (!invite)
|
|
1979
|
+
throw notFound("Invite not found");
|
|
1980
|
+
if (invite.inviteType === "bootstrap_ceo") {
|
|
1981
|
+
await assertInstanceAdmin(req);
|
|
1982
|
+
}
|
|
1983
|
+
else {
|
|
1984
|
+
if (!invite.companyId)
|
|
1985
|
+
throw conflict("Invite is missing company scope");
|
|
1986
|
+
await assertCompanyPermission(req, invite.companyId, "users:invite");
|
|
1987
|
+
}
|
|
1988
|
+
if (invite.acceptedAt)
|
|
1989
|
+
throw conflict("Invite already consumed");
|
|
1990
|
+
if (invite.revokedAt)
|
|
1991
|
+
return res.json(invite);
|
|
1992
|
+
const revoked = await db
|
|
1993
|
+
.update(invites)
|
|
1994
|
+
.set({ revokedAt: new Date(), updatedAt: new Date() })
|
|
1995
|
+
.where(eq(invites.id, id))
|
|
1996
|
+
.returning()
|
|
1997
|
+
.then((rows) => rows[0]);
|
|
1998
|
+
if (invite.companyId) {
|
|
1999
|
+
await logActivity(db, {
|
|
2000
|
+
companyId: invite.companyId,
|
|
2001
|
+
actorType: req.actor.type === "agent" ? "agent" : "user",
|
|
2002
|
+
actorId: req.actor.type === "agent"
|
|
2003
|
+
? req.actor.agentId ?? "unknown-agent"
|
|
2004
|
+
: req.actor.userId ?? "board",
|
|
2005
|
+
action: "invite.revoked",
|
|
2006
|
+
entityType: "invite",
|
|
2007
|
+
entityId: id
|
|
2008
|
+
});
|
|
2009
|
+
}
|
|
2010
|
+
res.json(revoked);
|
|
2011
|
+
});
|
|
2012
|
+
router.get("/companies/:companyId/join-requests", async (req, res) => {
|
|
2013
|
+
const companyId = req.params.companyId;
|
|
2014
|
+
await assertCompanyPermission(req, companyId, "joins:approve");
|
|
2015
|
+
const query = listJoinRequestsQuerySchema.parse(req.query);
|
|
2016
|
+
const all = await db
|
|
2017
|
+
.select()
|
|
2018
|
+
.from(joinRequests)
|
|
2019
|
+
.where(eq(joinRequests.companyId, companyId))
|
|
2020
|
+
.orderBy(desc(joinRequests.createdAt));
|
|
2021
|
+
const filtered = all.filter((row) => {
|
|
2022
|
+
if (query.status && row.status !== query.status)
|
|
2023
|
+
return false;
|
|
2024
|
+
if (query.requestType && row.requestType !== query.requestType)
|
|
2025
|
+
return false;
|
|
2026
|
+
return true;
|
|
2027
|
+
});
|
|
2028
|
+
res.json(filtered.map(toJoinRequestResponse));
|
|
2029
|
+
});
|
|
2030
|
+
router.post("/companies/:companyId/join-requests/:requestId/approve", async (req, res) => {
|
|
2031
|
+
const companyId = req.params.companyId;
|
|
2032
|
+
const requestId = req.params.requestId;
|
|
2033
|
+
await assertCompanyPermission(req, companyId, "joins:approve");
|
|
2034
|
+
const existing = await db
|
|
2035
|
+
.select()
|
|
2036
|
+
.from(joinRequests)
|
|
2037
|
+
.where(and(eq(joinRequests.companyId, companyId), eq(joinRequests.id, requestId)))
|
|
2038
|
+
.then((rows) => rows[0] ?? null);
|
|
2039
|
+
if (!existing)
|
|
2040
|
+
throw notFound("Join request not found");
|
|
2041
|
+
if (existing.status !== "pending_approval")
|
|
2042
|
+
throw conflict("Join request is not pending");
|
|
2043
|
+
const invite = await db
|
|
2044
|
+
.select()
|
|
2045
|
+
.from(invites)
|
|
2046
|
+
.where(eq(invites.id, existing.inviteId))
|
|
2047
|
+
.then((rows) => rows[0] ?? null);
|
|
2048
|
+
if (!invite)
|
|
2049
|
+
throw notFound("Invite not found");
|
|
2050
|
+
let createdAgentId = existing.createdAgentId ?? null;
|
|
2051
|
+
if (existing.requestType === "human") {
|
|
2052
|
+
if (!existing.requestingUserId)
|
|
2053
|
+
throw conflict("Join request missing user identity");
|
|
2054
|
+
await access.ensureMembership(companyId, "user", existing.requestingUserId, "member", "active");
|
|
2055
|
+
const grants = grantsFromDefaults(invite.defaultsPayload, "human");
|
|
2056
|
+
await access.setPrincipalGrants(companyId, "user", existing.requestingUserId, grants, req.actor.userId ?? null);
|
|
2057
|
+
}
|
|
2058
|
+
else {
|
|
2059
|
+
const existingAgents = await agents.list(companyId);
|
|
2060
|
+
const managerId = resolveJoinRequestAgentManagerId(existingAgents);
|
|
2061
|
+
if (!managerId) {
|
|
2062
|
+
throw conflict("Join request cannot be approved because this company has no active CEO");
|
|
2063
|
+
}
|
|
2064
|
+
const agentName = deduplicateAgentName(existing.agentName ?? "New Agent", existingAgents.map((a) => ({
|
|
2065
|
+
id: a.id,
|
|
2066
|
+
name: a.name,
|
|
2067
|
+
status: a.status
|
|
2068
|
+
})));
|
|
2069
|
+
const created = await agents.create(companyId, {
|
|
2070
|
+
name: agentName,
|
|
2071
|
+
role: "general",
|
|
2072
|
+
title: null,
|
|
2073
|
+
status: "idle",
|
|
2074
|
+
reportsTo: managerId,
|
|
2075
|
+
capabilities: existing.capabilities ?? null,
|
|
2076
|
+
adapterType: existing.adapterType ?? "process",
|
|
2077
|
+
adapterConfig: existing.agentDefaultsPayload &&
|
|
2078
|
+
typeof existing.agentDefaultsPayload === "object"
|
|
2079
|
+
? existing.agentDefaultsPayload
|
|
2080
|
+
: {},
|
|
2081
|
+
runtimeConfig: {},
|
|
2082
|
+
budgetMonthlyCents: 0,
|
|
2083
|
+
spentMonthlyCents: 0,
|
|
2084
|
+
permissions: {},
|
|
2085
|
+
lastHeartbeatAt: null,
|
|
2086
|
+
metadata: null
|
|
2087
|
+
});
|
|
2088
|
+
createdAgentId = created.id;
|
|
2089
|
+
await access.ensureMembership(companyId, "agent", created.id, "member", "active");
|
|
2090
|
+
const grants = agentJoinGrantsFromDefaults(invite.defaultsPayload);
|
|
2091
|
+
await access.setPrincipalGrants(companyId, "agent", created.id, grants, req.actor.userId ?? null);
|
|
2092
|
+
}
|
|
2093
|
+
const approved = await db
|
|
2094
|
+
.update(joinRequests)
|
|
2095
|
+
.set({
|
|
2096
|
+
status: "approved",
|
|
2097
|
+
approvedByUserId: req.actor.userId ?? (isLocalImplicit(req) ? "local-board" : null),
|
|
2098
|
+
approvedAt: new Date(),
|
|
2099
|
+
createdAgentId,
|
|
2100
|
+
updatedAt: new Date()
|
|
2101
|
+
})
|
|
2102
|
+
.where(eq(joinRequests.id, requestId))
|
|
2103
|
+
.returning()
|
|
2104
|
+
.then((rows) => rows[0]);
|
|
2105
|
+
await logActivity(db, {
|
|
2106
|
+
companyId,
|
|
2107
|
+
actorType: "user",
|
|
2108
|
+
actorId: req.actor.userId ?? "board",
|
|
2109
|
+
action: "join.approved",
|
|
2110
|
+
entityType: "join_request",
|
|
2111
|
+
entityId: requestId,
|
|
2112
|
+
details: { requestType: existing.requestType, createdAgentId }
|
|
2113
|
+
});
|
|
2114
|
+
if (createdAgentId) {
|
|
2115
|
+
void notifyHireApproved(db, {
|
|
2116
|
+
companyId,
|
|
2117
|
+
agentId: createdAgentId,
|
|
2118
|
+
source: "join_request",
|
|
2119
|
+
sourceId: requestId,
|
|
2120
|
+
approvedAt: new Date()
|
|
2121
|
+
}).catch(() => { });
|
|
2122
|
+
}
|
|
2123
|
+
res.json(toJoinRequestResponse(approved));
|
|
2124
|
+
});
|
|
2125
|
+
router.post("/companies/:companyId/join-requests/:requestId/reject", async (req, res) => {
|
|
2126
|
+
const companyId = req.params.companyId;
|
|
2127
|
+
const requestId = req.params.requestId;
|
|
2128
|
+
await assertCompanyPermission(req, companyId, "joins:approve");
|
|
2129
|
+
const existing = await db
|
|
2130
|
+
.select()
|
|
2131
|
+
.from(joinRequests)
|
|
2132
|
+
.where(and(eq(joinRequests.companyId, companyId), eq(joinRequests.id, requestId)))
|
|
2133
|
+
.then((rows) => rows[0] ?? null);
|
|
2134
|
+
if (!existing)
|
|
2135
|
+
throw notFound("Join request not found");
|
|
2136
|
+
if (existing.status !== "pending_approval")
|
|
2137
|
+
throw conflict("Join request is not pending");
|
|
2138
|
+
const rejected = await db
|
|
2139
|
+
.update(joinRequests)
|
|
2140
|
+
.set({
|
|
2141
|
+
status: "rejected",
|
|
2142
|
+
rejectedByUserId: req.actor.userId ?? (isLocalImplicit(req) ? "local-board" : null),
|
|
2143
|
+
rejectedAt: new Date(),
|
|
2144
|
+
updatedAt: new Date()
|
|
2145
|
+
})
|
|
2146
|
+
.where(eq(joinRequests.id, requestId))
|
|
2147
|
+
.returning()
|
|
2148
|
+
.then((rows) => rows[0]);
|
|
2149
|
+
await logActivity(db, {
|
|
2150
|
+
companyId,
|
|
2151
|
+
actorType: "user",
|
|
2152
|
+
actorId: req.actor.userId ?? "board",
|
|
2153
|
+
action: "join.rejected",
|
|
2154
|
+
entityType: "join_request",
|
|
2155
|
+
entityId: requestId,
|
|
2156
|
+
details: { requestType: existing.requestType }
|
|
2157
|
+
});
|
|
2158
|
+
res.json(toJoinRequestResponse(rejected));
|
|
2159
|
+
});
|
|
2160
|
+
router.post("/join-requests/:requestId/claim-api-key", validate(claimJoinRequestApiKeySchema), async (req, res) => {
|
|
2161
|
+
const requestId = req.params.requestId;
|
|
2162
|
+
const presentedClaimSecretHash = hashToken(req.body.claimSecret);
|
|
2163
|
+
const joinRequest = await db
|
|
2164
|
+
.select()
|
|
2165
|
+
.from(joinRequests)
|
|
2166
|
+
.where(eq(joinRequests.id, requestId))
|
|
2167
|
+
.then((rows) => rows[0] ?? null);
|
|
2168
|
+
if (!joinRequest)
|
|
2169
|
+
throw notFound("Join request not found");
|
|
2170
|
+
if (joinRequest.requestType !== "agent")
|
|
2171
|
+
throw badRequest("Only agent join requests can claim API keys");
|
|
2172
|
+
if (joinRequest.status !== "approved")
|
|
2173
|
+
throw conflict("Join request must be approved before key claim");
|
|
2174
|
+
if (!joinRequest.createdAgentId)
|
|
2175
|
+
throw conflict("Join request has no created agent");
|
|
2176
|
+
if (!joinRequest.claimSecretHash)
|
|
2177
|
+
throw conflict("Join request is missing claim secret metadata");
|
|
2178
|
+
if (!tokenHashesMatch(joinRequest.claimSecretHash, presentedClaimSecretHash)) {
|
|
2179
|
+
throw forbidden("Invalid claim secret");
|
|
2180
|
+
}
|
|
2181
|
+
if (joinRequest.claimSecretExpiresAt &&
|
|
2182
|
+
joinRequest.claimSecretExpiresAt.getTime() <= Date.now()) {
|
|
2183
|
+
throw conflict("Claim secret expired");
|
|
2184
|
+
}
|
|
2185
|
+
if (joinRequest.claimSecretConsumedAt)
|
|
2186
|
+
throw conflict("Claim secret already used");
|
|
2187
|
+
const existingKey = await db
|
|
2188
|
+
.select({ id: agentApiKeys.id })
|
|
2189
|
+
.from(agentApiKeys)
|
|
2190
|
+
.where(eq(agentApiKeys.agentId, joinRequest.createdAgentId))
|
|
2191
|
+
.then((rows) => rows[0] ?? null);
|
|
2192
|
+
if (existingKey)
|
|
2193
|
+
throw conflict("API key already claimed");
|
|
2194
|
+
const consumed = await db
|
|
2195
|
+
.update(joinRequests)
|
|
2196
|
+
.set({ claimSecretConsumedAt: new Date(), updatedAt: new Date() })
|
|
2197
|
+
.where(and(eq(joinRequests.id, requestId), isNull(joinRequests.claimSecretConsumedAt)))
|
|
2198
|
+
.returning({ id: joinRequests.id })
|
|
2199
|
+
.then((rows) => rows[0] ?? null);
|
|
2200
|
+
if (!consumed)
|
|
2201
|
+
throw conflict("Claim secret already used");
|
|
2202
|
+
const created = await agents.createApiKey(joinRequest.createdAgentId, "initial-join-key");
|
|
2203
|
+
await logActivity(db, {
|
|
2204
|
+
companyId: joinRequest.companyId,
|
|
2205
|
+
actorType: "system",
|
|
2206
|
+
actorId: "join-claim",
|
|
2207
|
+
action: "agent_api_key.claimed",
|
|
2208
|
+
entityType: "agent_api_key",
|
|
2209
|
+
entityId: created.id,
|
|
2210
|
+
details: {
|
|
2211
|
+
agentId: joinRequest.createdAgentId,
|
|
2212
|
+
joinRequestId: requestId
|
|
2213
|
+
}
|
|
2214
|
+
});
|
|
2215
|
+
res.status(201).json({
|
|
2216
|
+
keyId: created.id,
|
|
2217
|
+
token: created.token,
|
|
2218
|
+
agentId: joinRequest.createdAgentId,
|
|
2219
|
+
createdAt: created.createdAt
|
|
2220
|
+
});
|
|
2221
|
+
});
|
|
2222
|
+
router.get("/companies/:companyId/members", async (req, res) => {
|
|
2223
|
+
const companyId = req.params.companyId;
|
|
2224
|
+
await assertCompanyPermission(req, companyId, "users:manage_permissions");
|
|
2225
|
+
const members = await access.listMembers(companyId);
|
|
2226
|
+
res.json(members);
|
|
2227
|
+
});
|
|
2228
|
+
router.patch("/companies/:companyId/members/:memberId/permissions", validate(updateMemberPermissionsSchema), async (req, res) => {
|
|
2229
|
+
const companyId = req.params.companyId;
|
|
2230
|
+
const memberId = req.params.memberId;
|
|
2231
|
+
await assertCompanyPermission(req, companyId, "users:manage_permissions");
|
|
2232
|
+
const updated = await access.setMemberPermissions(companyId, memberId, req.body.grants ?? [], req.actor.userId ?? null);
|
|
2233
|
+
if (!updated)
|
|
2234
|
+
throw notFound("Member not found");
|
|
2235
|
+
res.json(updated);
|
|
2236
|
+
});
|
|
2237
|
+
router.post("/admin/users/:userId/promote-instance-admin", async (req, res) => {
|
|
2238
|
+
await assertInstanceAdmin(req);
|
|
2239
|
+
const userId = req.params.userId;
|
|
2240
|
+
const result = await access.promoteInstanceAdmin(userId);
|
|
2241
|
+
res.status(201).json(result);
|
|
2242
|
+
});
|
|
2243
|
+
router.post("/admin/users/:userId/demote-instance-admin", async (req, res) => {
|
|
2244
|
+
await assertInstanceAdmin(req);
|
|
2245
|
+
const userId = req.params.userId;
|
|
2246
|
+
const removed = await access.demoteInstanceAdmin(userId);
|
|
2247
|
+
if (!removed)
|
|
2248
|
+
throw notFound("Instance admin role not found");
|
|
2249
|
+
res.json(removed);
|
|
2250
|
+
});
|
|
2251
|
+
router.get("/admin/users/:userId/company-access", async (req, res) => {
|
|
2252
|
+
await assertInstanceAdmin(req);
|
|
2253
|
+
const userId = req.params.userId;
|
|
2254
|
+
const memberships = await access.listUserCompanyAccess(userId);
|
|
2255
|
+
res.json(memberships);
|
|
2256
|
+
});
|
|
2257
|
+
router.put("/admin/users/:userId/company-access", validate(updateUserCompanyAccessSchema), async (req, res) => {
|
|
2258
|
+
await assertInstanceAdmin(req);
|
|
2259
|
+
const userId = req.params.userId;
|
|
2260
|
+
const memberships = await access.setUserCompanyAccess(userId, req.body.companyIds ?? []);
|
|
2261
|
+
res.json(memberships);
|
|
2262
|
+
});
|
|
2263
|
+
return router;
|
|
2264
|
+
}
|
|
2265
|
+
//# sourceMappingURL=access.js.map
|