@blackbelt-technology/pi-agent-dashboard 0.10.0 → 0.11.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/AGENTS.md +2 -2
- package/README.md +47 -6
- package/docs/architecture.md +1369 -63
- package/package.json +14 -9
- package/packages/extension/package.json +5 -3
- package/packages/extension/src/bridge-handlers/dispatch.ts +57 -3
- package/packages/extension/src/bridge-handlers/instance.ts +10 -1
- package/packages/extension/src/bridge-handlers/lifecycle.ts +65 -26
- package/packages/extension/src/bridge-ticket-client.ts +61 -7
- package/packages/extension/src/bridge-tls-checks.ts +79 -0
- package/packages/extension/src/bridge.ts +41 -28
- package/packages/extension/src/canvas-tool.ts +2 -0
- package/packages/extension/src/command-handler.ts +80 -6
- package/packages/extension/src/connect-target.ts +23 -0
- package/packages/extension/src/connection.ts +30 -7
- package/packages/extension/src/dashboard-http-origin.ts +88 -0
- package/packages/extension/src/dev-build.ts +11 -1
- package/packages/extension/src/git-link-builder.ts +11 -2
- package/packages/extension/src/inbound-limits.ts +138 -0
- package/packages/extension/src/local-token-header.ts +77 -6
- package/packages/extension/src/model-refresh.ts +69 -0
- package/packages/extension/src/pinned-endpoint.ts +44 -0
- package/packages/extension/src/project-trust-live.ts +143 -0
- package/packages/extension/src/project-trust.ts +159 -20
- package/packages/extension/src/provider-register.ts +59 -18
- package/packages/extension/src/remote-registration-gate.ts +21 -21
- package/packages/extension/src/remote-upgrade-preparer.ts +104 -0
- package/packages/extension/src/role-model-tools.ts +47 -6
- package/packages/extension/src/server-auto-start.ts +1 -1
- package/packages/extension/src/server-proof-probe.ts +117 -0
- package/packages/extension/src/session-sync.ts +42 -12
- package/packages/extension/src/vault-delivery.ts +11 -1
- package/packages/server/package.json +8 -8
- package/packages/server/src/access/access-grants.ts +61 -8
- package/packages/server/src/access/access-health.ts +10 -0
- package/packages/server/src/access/access-plane.ts +5 -1
- package/packages/server/src/access/containment-gate.ts +55 -17
- package/packages/server/src/access/cwd-verdict.ts +3 -3
- package/packages/server/src/access/pi-trust-live.ts +244 -0
- package/packages/server/src/access/pi-trust-mirror-service.ts +44 -11
- package/packages/server/src/access/planes.ts +106 -1
- package/packages/server/src/access/preview-egress-store.ts +153 -0
- package/packages/server/src/access/prompt-channel.ts +5 -0
- package/packages/server/src/access/provisioning-wiring.ts +113 -0
- package/packages/server/src/access/provisioning.ts +763 -0
- package/packages/server/src/access/yolo-session.ts +54 -2
- package/packages/server/src/acp-bridge/acp-session-adapter.ts +8 -3
- package/packages/server/src/agent-events/agent-event-hub.ts +158 -0
- package/packages/server/src/auth/audit-log.ts +80 -0
- package/packages/server/src/auth/auth-plugin.ts +44 -25
- package/packages/server/src/auth/auth.ts +24 -4
- package/packages/server/src/auth/bearer-auth.ts +52 -12
- package/packages/server/src/auth/cors-origin.ts +76 -29
- package/packages/server/src/auth/csp-report-paths.ts +31 -0
- package/packages/server/src/auth/csp-report-sink.ts +302 -0
- package/packages/server/src/auth/csp-report-store.ts +406 -0
- package/packages/server/src/auth/csp.ts +105 -9
- package/packages/server/src/auth/dashboard-credential-store.ts +4 -0
- package/packages/server/src/auth/dashboard-state-caller.ts +29 -0
- package/packages/server/src/auth/local-proof-refusal-log.ts +89 -0
- package/packages/server/src/auth/local-proof.ts +69 -18
- package/packages/server/src/auth/localhost-guard.ts +48 -10
- package/packages/server/src/auth/nav-intent.ts +72 -0
- package/packages/server/src/auth/passkey/passkey-assets.ts +99 -0
- package/packages/server/src/auth/passkey/passkey-pages.ts +17 -81
- package/packages/server/src/auth/passkey/passkey-routes.ts +8 -0
- package/packages/server/src/auth/pi-legacy-credentials.ts +3 -0
- package/packages/server/src/auth/plugin-server-trust.ts +29 -0
- package/packages/server/src/auth/plugin-trust-store.ts +103 -0
- package/packages/server/src/auth/proven-tls.ts +45 -0
- package/packages/server/src/auth/provider-auth-storage.ts +6 -1
- package/packages/server/src/auth/radius-mcp.ts +1 -1
- package/packages/server/src/auth/request-principal.ts +32 -0
- package/packages/server/src/auth/secret-rotation.ts +246 -0
- package/packages/server/src/auth/secure-origin.ts +56 -0
- package/packages/server/src/auth/serve-app-host.ts +111 -11
- package/packages/server/src/auth/ws-ticket.ts +39 -1
- package/packages/server/src/auth/ws-upgrade-reject-log.ts +4 -1
- package/packages/server/src/browser-handlers/directory-handler.ts +23 -0
- package/packages/server/src/browser-handlers/folder-gate.ts +55 -0
- package/packages/server/src/browser-handlers/handler-context.ts +25 -2
- package/packages/server/src/browser-handlers/session-action-handler.ts +9 -1
- package/packages/server/src/browser-handlers/subscription-handler.ts +100 -2
- package/packages/server/src/browser-handlers/terminal-handler.ts +108 -10
- package/packages/server/src/canvas/canvas-accumulator.ts +35 -7
- package/packages/server/src/cli.ts +210 -39
- package/packages/server/src/config-api.ts +23 -1
- package/packages/server/src/config-snapshot.ts +48 -1
- package/packages/server/src/directory-service.ts +160 -54
- package/packages/server/src/event-wiring.ts +143 -108
- package/packages/server/src/git-worktree/git-operations.ts +44 -10
- package/packages/server/src/git-worktree/redact-git-text.ts +124 -0
- package/packages/server/src/git-worktree/ref-arg.ts +39 -0
- package/packages/server/src/git-worktree/worktree-init-trust.ts +43 -1
- package/packages/server/src/identity/http-road-classification.ts +13 -1
- package/packages/server/src/identity/ws-message-scope.ts +1 -0
- package/packages/server/src/identity/ws-road-classification.ts +1 -0
- package/packages/server/src/known-server-moves.ts +36 -15
- package/packages/server/src/lib/browse-roots.ts +118 -17
- package/packages/server/src/lib/client-dist.ts +36 -21
- package/packages/server/src/lib/dashboard-state-guard.ts +230 -0
- package/packages/server/src/lib/diagram-render.ts +4 -6
- package/packages/server/src/lib/eml.ts +3 -8
- package/packages/server/src/lib/file-cwd-admission.ts +145 -0
- package/packages/server/src/lib/grep-worker.ts +23 -0
- package/packages/server/src/lib/grep.ts +93 -7
- package/packages/server/src/lib/index-html.ts +81 -0
- package/packages/server/src/lib/office-preview.ts +2 -3
- package/packages/server/src/lib/path-containment.ts +7 -0
- package/packages/server/src/lib/resolve-file-mention.ts +11 -9
- package/packages/server/src/lib/route-admission.ts +80 -0
- package/packages/server/src/lib/writable-md-target.ts +4 -0
- package/packages/server/src/lifecycle/recovery-server.ts +65 -18
- package/packages/server/src/live-server/capability-redact.ts +15 -0
- package/packages/server/src/live-server/live-browser-gate.ts +22 -0
- package/packages/server/src/live-server/live-capability.ts +224 -17
- package/packages/server/src/live-server/live-csp-report.ts +63 -0
- package/packages/server/src/live-server/live-csp.ts +93 -0
- package/packages/server/src/live-server/live-egress.ts +435 -0
- package/packages/server/src/live-server/live-exposure.ts +149 -0
- package/packages/server/src/live-server/live-log.ts +21 -0
- package/packages/server/src/live-server/live-origin-scan.ts +298 -0
- package/packages/server/src/live-server/live-server-manager.ts +209 -33
- package/packages/server/src/live-server/live-server-proxy.ts +162 -17
- package/packages/server/src/live-server/live-static.ts +228 -0
- package/packages/server/src/openspec/dependencies-file.ts +122 -0
- package/packages/server/src/openspec/openspec-change-watcher.ts +3 -1
- package/packages/server/src/openspec/openspec-dependency-inputs.ts +281 -0
- package/packages/server/src/openspec/openspec-poll-fs-helpers.ts +72 -26
- package/packages/server/src/openspec/openspec-poll-worker-pool.ts +48 -12
- package/packages/server/src/openspec/openspec-poll-worker.ts +95 -9
- package/packages/server/src/openspec/workflow-schema-status.ts +379 -0
- package/packages/server/src/openspec/workflow-schema.ts +141 -267
- package/packages/server/src/package/npm-search-proxy.ts +5 -2
- package/packages/server/src/package/provider-probe.ts +8 -2
- package/packages/server/src/pairing/browser-gateway.ts +188 -12
- package/packages/server/src/pairing/device-token-services.ts +26 -0
- package/packages/server/src/pairing/paired-devices.ts +335 -22
- package/packages/server/src/pairing/pairing.ts +34 -4
- package/packages/server/src/pairing/socket-locality.ts +26 -0
- package/packages/server/src/persistence/preferences-store.ts +9 -0
- package/packages/server/src/pi/bridge-channel.ts +33 -0
- package/packages/server/src/pi/bridge-upgrade-auth.ts +18 -3
- package/packages/server/src/pi/gateway-listeners.ts +9 -3
- package/packages/server/src/pi/host-project-trust.ts +14 -6
- package/packages/server/src/pi/pi-gateway.ts +191 -21
- package/packages/server/src/pi/resource-toggle-trust.ts +1 -1
- package/packages/server/src/plugin-discovery-wiring.ts +142 -0
- package/packages/server/src/plugin-event-seam.ts +116 -4
- package/packages/server/src/plugin-runtime-clients.ts +89 -0
- package/packages/server/src/routes/access-routes.ts +159 -9
- package/packages/server/src/routes/agent-event-stream-routes.ts +137 -0
- package/packages/server/src/routes/canvas-types-routes.ts +20 -6
- package/packages/server/src/routes/csp-violations-routes.ts +162 -0
- package/packages/server/src/routes/file-routes.ts +329 -209
- package/packages/server/src/routes/file-write-binary-routes.ts +77 -20
- package/packages/server/src/routes/folder-project-routes.ts +18 -12
- package/packages/server/src/routes/git-routes.ts +319 -203
- package/packages/server/src/routes/grep-routes.ts +38 -14
- package/packages/server/src/routes/known-servers-routes.ts +189 -91
- package/packages/server/src/routes/live-server-routes.ts +378 -15
- package/packages/server/src/routes/local-proof-routes.ts +14 -0
- package/packages/server/src/routes/nav-intent-routes.ts +46 -0
- package/packages/server/src/routes/openspec-group-routes.ts +53 -44
- package/packages/server/src/routes/openspec-routes.ts +379 -28
- package/packages/server/src/routes/package-routes.ts +58 -10
- package/packages/server/src/routes/pairing-routes.ts +146 -10
- package/packages/server/src/routes/pi-trust-query-routes.ts +330 -0
- package/packages/server/src/routes/plugin-activation-routes.ts +59 -0
- package/packages/server/src/routes/plugin-runtime-client-routes.ts +149 -0
- package/packages/server/src/routes/provider-auth-routes.ts +15 -2
- package/packages/server/src/routes/resource-activation-routes.ts +18 -4
- package/packages/server/src/routes/session-routes.ts +51 -4
- package/packages/server/src/routes/system-routes.ts +84 -15
- package/packages/server/src/routes/ui-link-base.ts +88 -0
- package/packages/server/src/runtime-overlay/runtime-io.ts +2 -9
- package/packages/server/src/server.ts +648 -137
- package/packages/server/src/session/hydration-state.ts +148 -0
- package/packages/server/src/session/memory-session-manager.ts +7 -0
- package/packages/server/src/session/replay-exit-controller.ts +221 -0
- package/packages/server/src/session/retained-transcript.ts +9 -2
- package/packages/server/src/session/session-load-worker.ts +11 -2
- package/packages/server/src/spawn-process/headless-pid-registry.ts +14 -9
- package/packages/server/src/terminal/terminal-manager.ts +54 -46
- package/packages/server/src/tls/tls-bridge-route.ts +61 -0
- package/packages/server/src/tls/tls-config-validation.ts +2 -0
- package/packages/server/src/vault/device-expiry-sweep.ts +36 -0
- package/packages/server/src/vault/vault-delivery-hub.ts +155 -25
- package/packages/server/src/watch-files-handler.ts +66 -0
- package/packages/shared/package.json +1 -1
- package/packages/shared/src/browser-protocol.ts +148 -2
- package/packages/shared/src/canvas-declare.ts +27 -0
- package/packages/shared/src/config.ts +372 -53
- package/packages/shared/src/containment-guard.ts +35 -0
- package/packages/shared/src/dashboard-plugin/anthropic-peer-names.ts +9 -0
- package/packages/shared/src/dashboard-plugin/event-type-owners.ts +50 -0
- package/packages/shared/src/dashboard-plugin/file-handler.ts +2 -0
- package/packages/shared/src/dashboard-plugin/host-api.ts +61 -0
- package/packages/shared/src/dashboard-plugin/host-fx-classes.ts +23 -0
- package/packages/shared/src/dashboard-plugin/host-import-map.ts +38 -0
- package/packages/shared/src/dashboard-plugin/index.ts +2 -0
- package/packages/shared/src/dashboard-plugin/manifest-types.ts +54 -1
- package/packages/shared/src/dashboard-plugin/plugin-status.ts +54 -0
- package/packages/shared/src/dashboard-plugin/slot-props.ts +45 -3
- package/packages/shared/src/dashboard-plugin/slot-types.ts +8 -0
- package/packages/shared/src/dashboard-plugin/subagent-types.ts +219 -0
- package/packages/shared/src/dashboard-plugin/ui-primitives.ts +28 -0
- package/packages/shared/src/display-prefs.ts +13 -0
- package/packages/shared/src/doctor-core.ts +94 -27
- package/packages/shared/src/live-server.ts +141 -0
- package/packages/shared/src/local-proof-signal.ts +16 -0
- package/packages/shared/src/loopback-host.ts +26 -0
- package/packages/shared/src/mcp/verb-tiers.generated.ts +178 -0
- package/packages/shared/src/mdns-discovery.ts +25 -6
- package/packages/shared/src/nav-intent.ts +29 -0
- package/packages/shared/src/openspec-dependencies.ts +760 -0
- package/packages/shared/src/openspec-poller.ts +3 -2
- package/packages/shared/src/pairing-knock-client.ts +44 -4
- package/packages/shared/src/pi-trust-live-query.ts +93 -0
- package/packages/shared/src/pi-trust-mirror-snapshot.ts +5 -7
- package/packages/shared/src/pi-trust-mirror-types.ts +36 -3
- package/packages/shared/src/pi-trust-mirror.ts +29 -3
- package/packages/shared/src/pi-trust-resource-digest.ts +255 -0
- package/packages/shared/src/platform/ensure-bundled-git.ts +57 -34
- package/packages/shared/src/platform/git-source.ts +88 -26
- package/packages/shared/src/platform/git.ts +14 -8
- package/packages/shared/src/platform/process.ts +48 -4
- package/packages/shared/src/platform/resolve-pi-shell.ts +76 -0
- package/packages/shared/src/platform/select-git-source.ts +7 -0
- package/packages/shared/src/plugin-route-cwd.ts +95 -0
- package/packages/shared/src/preview-egress.ts +138 -0
- package/packages/shared/src/project-root.ts +16 -0
- package/packages/shared/src/protocol.ts +40 -1
- package/packages/shared/src/recommended-extensions.ts +18 -0
- package/packages/shared/src/recovery-timing.ts +27 -0
- package/packages/shared/src/remote-credentials.ts +63 -0
- package/packages/shared/src/rest-api.ts +55 -8
- package/packages/shared/src/route-tiers.ts +55 -1
- package/packages/shared/src/runtime-overlay/archive-safety.d.mts +2 -0
- package/packages/shared/src/runtime-overlay/archive-safety.mjs +33 -0
- package/packages/shared/src/runtime-overlay/manifest.d.mts +7 -0
- package/packages/shared/src/runtime-overlay/manifest.mjs +22 -2
- package/packages/shared/src/safe-local-path.ts +24 -0
- package/packages/shared/src/sanitize-profiles.ts +98 -0
- package/packages/shared/src/server-launcher.ts +9 -1
- package/packages/shared/src/server-pinning.ts +55 -2
- package/packages/shared/src/server-routes.ts +462 -0
- package/packages/shared/src/session-ui-path.ts +11 -0
- package/packages/shared/src/tls-only-token.ts +16 -0
- package/packages/shared/src/tool-registry/definitions.ts +5 -5
- package/packages/shared/src/tool-registry/strategies.ts +12 -11
- package/packages/shared/src/types.ts +66 -0
- package/packages/shared/src/url-policy.ts +96 -0
- package/packages/shared/src/vault-delivery.ts +15 -0
- package/packages/shared/src/ws-message-tiers.ts +1 -0
|
@@ -2,20 +2,26 @@
|
|
|
2
2
|
* Content-search REST route (localhost-only): `GET /api/grep`.
|
|
3
3
|
*
|
|
4
4
|
* Prefers `ripgrep`, falls back to a bounded in-process scan. Applies the same
|
|
5
|
-
* security gates as `/api/file`: `cwd` must be
|
|
6
|
-
*
|
|
5
|
+
* security gates as `/api/file`: `cwd` must be admitted by the shared cwd guard
|
|
6
|
+
* (session, pinned or workspace folder, or a worktree / main checkout of a known
|
|
7
|
+
* repository); every returned match path must resolve within `cwd` (and its
|
|
8
|
+
* canonical form; traversal excluded).
|
|
7
9
|
*
|
|
8
|
-
* See change: split-editor-workspace.
|
|
10
|
+
* See change: split-editor-workspace, core-file-cwd-admission.
|
|
9
11
|
*/
|
|
10
12
|
|
|
11
13
|
import path from "node:path";
|
|
14
|
+
import { containmentAllows } from "@blackbelt-technology/pi-dashboard-shared/containment-guard.js";
|
|
12
15
|
import type { ApiResponse } from "@blackbelt-technology/pi-dashboard-shared/types.js";
|
|
13
16
|
import type { FastifyInstance } from "fastify";
|
|
14
17
|
import { grantedSubjects } from "../access/access-grants.js";
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
18
|
+
import { decidePassive } from "../access/containment-gate.js";
|
|
19
|
+
import { admitFileCwd, cwdAnchors } from "../lib/file-cwd-admission.js";
|
|
20
|
+
import { GrepTimeoutError, runGrep } from "../lib/grep.js";
|
|
21
|
+
import type { RouteAdmissionDeps } from "../lib/route-admission.js";
|
|
17
22
|
import { detectRipgrep } from "../ripgrep-detection.js";
|
|
18
23
|
import type { SessionManager } from "../session/memory-session-manager.js";
|
|
24
|
+
import { sendGateFailure } from "./file-routes.js";
|
|
19
25
|
import type { NetworkGuard } from "./route-deps.js";
|
|
20
26
|
|
|
21
27
|
/** Minimum query length (mirrors the client min-3-char guard). */
|
|
@@ -26,9 +32,16 @@ export function registerGrepRoutes(
|
|
|
26
32
|
deps: {
|
|
27
33
|
sessionManager: SessionManager;
|
|
28
34
|
networkGuard: NetworkGuard;
|
|
35
|
+
/** Shared cwd admission. Absent → the known set is the `sessionManager`'s session cwds only. */
|
|
36
|
+
routeAdmission?: RouteAdmissionDeps;
|
|
37
|
+
/** Test seams for the fallback scan: timeout and worker entry. Default `RG_TIMEOUT_MS` + `grep-worker.ts`. */
|
|
38
|
+
grep?: { scanTimeoutMs?: number; scanWorkerUrl?: string };
|
|
29
39
|
},
|
|
30
40
|
) {
|
|
31
41
|
const { sessionManager, networkGuard } = deps;
|
|
42
|
+
const routeAdmission: RouteAdmissionDeps = deps.routeAdmission ?? {
|
|
43
|
+
knownCwds: () => sessionManager.listAll().map((s) => s.cwd),
|
|
44
|
+
};
|
|
32
45
|
|
|
33
46
|
fastify.get<{ Querystring: { cwd?: string; q?: string; regex?: string } }>(
|
|
34
47
|
"/api/grep",
|
|
@@ -47,13 +60,24 @@ export function registerGrepRoutes(
|
|
|
47
60
|
return { success: false, error: `q must be at least ${MIN_QUERY_LEN} characters` } satisfies ApiResponse;
|
|
48
61
|
}
|
|
49
62
|
|
|
50
|
-
// Gate 1 — cwd must be
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
}
|
|
63
|
+
// Gate 1 — cwd must be admitted by the shared guard (mirrors /api/file).
|
|
64
|
+
const admitted = await admitFileCwd(cwd, routeAdmission, { reply });
|
|
65
|
+
if (!admitted.ok) return sendGateFailure(reply, admitted.failure);
|
|
66
|
+
const anchors = cwdAnchors(admitted);
|
|
55
67
|
|
|
56
|
-
let matches
|
|
68
|
+
let matches: Awaited<ReturnType<typeof runGrep>>;
|
|
69
|
+
try {
|
|
70
|
+
matches = await runGrep(admitted.cwd, q, { regex, rgPath: detectRipgrep(), ...deps.grep });
|
|
71
|
+
} catch (err) {
|
|
72
|
+
// A fallback scan that outlived its timeout (e.g. a catastrophic regexp) → 504; any other
|
|
73
|
+
// scan failure (worker died) → 500. Never a 200 with stale or partial matches.
|
|
74
|
+
if (err instanceof GrepTimeoutError) {
|
|
75
|
+
reply.code(504);
|
|
76
|
+
return { success: false, error: "search timed out" } satisfies ApiResponse;
|
|
77
|
+
}
|
|
78
|
+
reply.code(500);
|
|
79
|
+
return { success: false, error: "search failed" } satisfies ApiResponse;
|
|
80
|
+
}
|
|
57
81
|
|
|
58
82
|
// Gate 2 — containment: drop any match that resolves outside cwd. rg/JS
|
|
59
83
|
// scan already stay under cwd, so this is a defensive backstop.
|
|
@@ -64,9 +88,9 @@ export function registerGrepRoutes(
|
|
|
64
88
|
const grantSubjects = grantedSubjects();
|
|
65
89
|
const contained = await Promise.all(
|
|
66
90
|
matches.map(async (m) => {
|
|
67
|
-
const resolvedMatch = path.resolve(cwd, m.path);
|
|
68
|
-
|
|
69
|
-
return (
|
|
91
|
+
const resolvedMatch = path.resolve(admitted.cwd, m.path);
|
|
92
|
+
const verdict = await decidePassive(resolvedMatch, anchors, { allowGrant: true, grantSubjects });
|
|
93
|
+
return containmentAllows(verdict, resolvedMatch) ? m : null;
|
|
70
94
|
}),
|
|
71
95
|
);
|
|
72
96
|
matches = contained.filter((m): m is NonNullable<typeof m> => m !== null);
|
|
@@ -12,7 +12,13 @@
|
|
|
12
12
|
* each write re-reads config, re-validates, and aborts if its target entry has
|
|
13
13
|
* since been removed.
|
|
14
14
|
*
|
|
15
|
-
*
|
|
15
|
+
* A server is its identity: an entry holds `routes[]` (addresses at which it
|
|
16
|
+
* answers) and the `host`/`port` mirror of its primary route. An add that
|
|
17
|
+
* proves a fingerprint attaches its route to the entry holding it (D1, D6).
|
|
18
|
+
* Every challenge toward an operator-supplied host is bounded: http/https only,
|
|
19
|
+
* no redirects, 2 s, 4 KiB response cap, normal TLS verification (D2).
|
|
20
|
+
*
|
|
21
|
+
* See change: stabilize-mdns-server-identity (D6, D7), group-servers-by-identity (D1, D2, D6, D10).
|
|
16
22
|
*/
|
|
17
23
|
import dns from "node:dns";
|
|
18
24
|
import net from "node:net";
|
|
@@ -26,12 +32,21 @@ import type {
|
|
|
26
32
|
AddKnownServerRequest,
|
|
27
33
|
DiscoveredServerInfo,
|
|
28
34
|
KnownServerListEntry,
|
|
35
|
+
KnownServerProbeRequest,
|
|
29
36
|
KnownServerProbeResult,
|
|
30
37
|
RemoveKnownServerRequest,
|
|
31
38
|
} from "@blackbelt-technology/pi-dashboard-shared/rest-api.js";
|
|
32
|
-
import { loadConfig } from "@blackbelt-technology/pi-dashboard-shared/config.js";
|
|
39
|
+
import { knownServersNeedMigration, loadConfig, toStoredKnownServers } from "@blackbelt-technology/pi-dashboard-shared/config.js";
|
|
33
40
|
import { formatHostPort, isValidHost, normalizeHostKey } from "@blackbelt-technology/pi-dashboard-shared/host-port.js";
|
|
34
41
|
import { type ProveResult, proveServerIdentity } from "@blackbelt-technology/pi-dashboard-shared/server-pinning.js";
|
|
42
|
+
import {
|
|
43
|
+
findAttachTarget,
|
|
44
|
+
primaryRoute,
|
|
45
|
+
ROUTE_SCHEMES,
|
|
46
|
+
type Route,
|
|
47
|
+
type RouteScheme,
|
|
48
|
+
routeKey,
|
|
49
|
+
} from "@blackbelt-technology/pi-dashboard-shared/server-routes.js";
|
|
35
50
|
import type { HostAdmissionOptions } from "../auth/host-admission.js";
|
|
36
51
|
import type { LocalTrustContext } from "../auth/local-proof.js";
|
|
37
52
|
import { writeConfigPartial } from "../config-api.js";
|
|
@@ -64,12 +79,14 @@ export interface KnownServersRouteDeps {
|
|
|
64
79
|
localToken?: string;
|
|
65
80
|
localTrust?: LocalTrustContext;
|
|
66
81
|
hostAdmission: () => HostAdmissionOptions;
|
|
67
|
-
/** Identity-challenge seam (default: {@link proveServerIdentity}
|
|
82
|
+
/** Identity-challenge seam (default: {@link proveServerIdentity} over `fetchImpl`, 2 s). */
|
|
68
83
|
prove?: (baseUrl: string) => Promise<ProveResult>;
|
|
69
84
|
/** Name-resolution seam for the probe. */
|
|
70
85
|
lookup?: (host: string) => Promise<unknown>;
|
|
71
86
|
fetchImpl?: typeof fetch;
|
|
72
87
|
moves?: KnownServerMoves;
|
|
88
|
+
/** This server's own fingerprint: an address proving it is this dashboard itself (`self_address`), never a peer. */
|
|
89
|
+
ownFingerprint?: () => string | undefined;
|
|
73
90
|
log?: (message: string) => void;
|
|
74
91
|
/** Budget overrides (tests shrink them; production uses the defaults). */
|
|
75
92
|
timeouts?: { challengeMs?: number; dnsMs?: number; httpMs?: number };
|
|
@@ -79,6 +96,16 @@ const sameAddress = (a: { host: string; port: number }, b: { host: string; port:
|
|
|
79
96
|
a.port === b.port && normalizeHostKey(a.host) === normalizeHostKey(b.host);
|
|
80
97
|
|
|
81
98
|
const short = (fingerprint: string) => fingerprint.replace(/^sha256:/, "").slice(0, 16);
|
|
99
|
+
/** `sha256:` + the first 16 characters: enough to correlate, never the whole fingerprint (D10). */
|
|
100
|
+
const shortFp = (fingerprint: string) => `sha256:${short(fingerprint)}`;
|
|
101
|
+
/** `scheme://host:port` of a route, with the host in its normalised spelling. */
|
|
102
|
+
const routeUrl = (r: Pick<Route, "host" | "port" | "scheme">) =>
|
|
103
|
+
// Literal scheme: only the two allowlisted values ever reach the request URL.
|
|
104
|
+
`${r.scheme === "https" ? "https" : "http"}://${formatHostPort(r.host, r.port)}`;
|
|
105
|
+
const holdsRoute = (e: KnownServer, r: Route) => e.routes.some((x) => routeKey(x) === routeKey(r));
|
|
106
|
+
/** Body `scheme`: absent → `http`; anything but `http` / `https` → null (`400 invalid_scheme`). */
|
|
107
|
+
const parseScheme = (input: unknown): RouteScheme | null =>
|
|
108
|
+
input === undefined ? "http" : ROUTE_SCHEMES.includes(input as RouteScheme) ? (input as RouteScheme) : null;
|
|
82
109
|
|
|
83
110
|
/** Reject after `ms`, clearing its timer when the race settles. */
|
|
84
111
|
function withTimeout<T>(p: Promise<T>, ms: number, onTimeout: () => T): Promise<T> {
|
|
@@ -124,17 +151,56 @@ export function registerKnownServersRoutes(fastify: FastifyInstance, deps: Known
|
|
|
124
151
|
const challengeMs = deps.timeouts?.challengeMs ?? CHALLENGE_TIMEOUT_MS;
|
|
125
152
|
const dnsMs = deps.timeouts?.dnsMs ?? PROBE_DNS_TIMEOUT_MS;
|
|
126
153
|
const httpMs = deps.timeouts?.httpMs ?? PROBE_HTTP_TIMEOUT_MS;
|
|
127
|
-
const proveRaw =
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
154
|
+
const proveRaw =
|
|
155
|
+
deps.prove ??
|
|
156
|
+
((baseUrl: string) => proveServerIdentity(baseUrl, { timeoutMs: challengeMs, ...(deps.fetchImpl ? { fetchImpl: deps.fetchImpl } : {}) }));
|
|
157
|
+
/** Bounded identity challenge over the route's own scheme: a hanging target cannot hold the request. */
|
|
158
|
+
const prove = (host: string, port: number, scheme: RouteScheme): Promise<ProveResult> =>
|
|
159
|
+
withTimeout(proveRaw(routeUrl({ host, port, scheme })), challengeMs, () => ({
|
|
131
160
|
refused: "challenge timed out",
|
|
132
161
|
}));
|
|
133
162
|
const provedFingerprint = (r: ProveResult): string | undefined => ("proven" in r ? r.proven : undefined);
|
|
134
163
|
|
|
135
|
-
const readList = (): KnownServer[] => loadConfig().knownServers.map((e) => ({ ...e }));
|
|
136
|
-
|
|
137
|
-
|
|
164
|
+
const readList = (): KnownServer[] => loadConfig().knownServers.map((e) => ({ ...e, routes: e.routes.map((r) => ({ ...r })) }));
|
|
165
|
+
/** The one write: always routes shape plus the `host`/`port` mirror; logs once for the first rewrite of a previous-shape file. */
|
|
166
|
+
const writeList = (list: KnownServer[]): { success: boolean; error?: string } => {
|
|
167
|
+
const migrating = list.length > 0 && knownServersNeedMigration();
|
|
168
|
+
const result = writeConfigPartial({ knownServers: toStoredKnownServers(list) });
|
|
169
|
+
if (result.success && migrating) log(`[known-servers] first written in routes shape (${list.length} entries)`);
|
|
170
|
+
return result;
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* `list[idx]` just proved (or newly holds) its fingerprint: fold every other entry that holds the
|
|
175
|
+
* same identity on the same instance (D1 rule) into it — it keeps its routes first, then gains
|
|
176
|
+
* the other's, keeps its label else takes the other's.
|
|
177
|
+
*/
|
|
178
|
+
/**
|
|
179
|
+
* One instance = a shared `http` route port, or one side has no `http` route at all (its https routes join the
|
|
180
|
+
* holder, D1). Two entries on different `http` ports stay two rows even though an https route could attach to either.
|
|
181
|
+
*/
|
|
182
|
+
function sameInstance(a: KnownServer, b: KnownServer): boolean {
|
|
183
|
+
const ports = (e: KnownServer) => new Set(e.routes.filter((r) => r.scheme === "http").map((r) => r.port));
|
|
184
|
+
const pa = ports(a);
|
|
185
|
+
const pb = ports(b);
|
|
186
|
+
return pa.size === 0 || pb.size === 0 || [...pa].some((p) => pb.has(p));
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function foldDuplicates(list: KnownServer[], idx: number): void {
|
|
190
|
+
const survivor = list[idx];
|
|
191
|
+
if (!survivor.fingerprint) return;
|
|
192
|
+
for (let j = list.length - 1; j >= 0; j--) {
|
|
193
|
+
if (j === idx) continue;
|
|
194
|
+
const other = list[j];
|
|
195
|
+
if (other.fingerprint !== survivor.fingerprint || !sameInstance(survivor, other)) continue;
|
|
196
|
+
const keys = new Set(survivor.routes.map(routeKey));
|
|
197
|
+
for (const r of other.routes) if (!keys.has(routeKey(r))) survivor.routes.push(r);
|
|
198
|
+
if (!survivor.label && other.label) survivor.label = other.label;
|
|
199
|
+
list.splice(j, 1);
|
|
200
|
+
if (j < idx) idx -= 1;
|
|
201
|
+
log(`[known-servers] merged duplicate identity: folded ${other.host}:${other.port} into ${survivor.host}:${survivor.port}`);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
138
204
|
|
|
139
205
|
// ── List ─────────────────────────────────────────────────────────────
|
|
140
206
|
fastify.get("/api/known-servers", { preHandler: networkGuard }, async (request) => {
|
|
@@ -145,7 +211,7 @@ export function registerKnownServersRoutes(fastify: FastifyInstance, deps: Known
|
|
|
145
211
|
return { success: true, data, canManage: await isOperator(request) };
|
|
146
212
|
});
|
|
147
213
|
|
|
148
|
-
// ── Add /
|
|
214
|
+
// ── Add / attach ─────────────────────────────────────────────────────
|
|
149
215
|
fastify.post<{ Body: AddKnownServerRequest }>(
|
|
150
216
|
"/api/known-servers",
|
|
151
217
|
{ preHandler: mutationGuard },
|
|
@@ -155,67 +221,63 @@ export function registerKnownServersRoutes(fastify: FastifyInstance, deps: Known
|
|
|
155
221
|
if (!host || typeof host !== "string" || !Number.isInteger(port) || port < 1 || port > 65535) {
|
|
156
222
|
return { success: false, error: "host and port are required" };
|
|
157
223
|
}
|
|
158
|
-
//
|
|
159
|
-
|
|
224
|
+
// Before ANY request: the scheme allowlist (the route is challenged over its own scheme) ...
|
|
225
|
+
const scheme = parseScheme((request.body as { scheme?: unknown }).scheme);
|
|
226
|
+
if (!scheme) return fail(reply, 400, "invalid_scheme");
|
|
227
|
+
// ... and the host charset: the host is placed in an outbound URL (identity challenge), so admit only
|
|
228
|
+
// DNS-name / IP-literal characters; no URL-authority trick (`@`, `/`, `#`, `?`) can redirect the request.
|
|
160
229
|
if (!/^[A-Za-z0-9._:[\]-]+$/.test(host) || !isValidHost(host)) return fail(reply, 400, "invalid_host");
|
|
161
|
-
|
|
230
|
+
const candidate: Route = { host, port, scheme, source: "saved" };
|
|
231
|
+
// Snapshot BEFORE the challenge: an entry that held the route then but is gone when the
|
|
162
232
|
// write runs was deleted meanwhile and must not be recreated.
|
|
163
|
-
const
|
|
233
|
+
const heldBefore = readList().some((e) => holdsRoute(e, candidate));
|
|
164
234
|
// `fingerprint` in the body is a hint only and is never persisted unless proven.
|
|
165
|
-
const proven = provedFingerprint(await prove(host, port));
|
|
235
|
+
const proven = provedFingerprint(await prove(host, port, scheme));
|
|
166
236
|
|
|
167
|
-
// The
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
237
|
+
// The address reaches THIS dashboard (e.g. a virtual-bridge address both machines hold): never a peer.
|
|
238
|
+
// Takes precedence over every other post-challenge outcome (incl. identity_changed); nothing is pinned.
|
|
239
|
+
if (proven && proven === deps.ownFingerprint?.()) {
|
|
240
|
+
log(`[known-servers] route refused: address reaches this dashboard itself ${routeUrl(candidate)} fp=${shortFp(proven)}`);
|
|
241
|
+
return fail(reply, 409, "self_address");
|
|
242
|
+
}
|
|
173
243
|
|
|
174
244
|
return enqueueKnownServersWrite((): ApiResponse<{ updated?: boolean }> & Record<string, unknown> => {
|
|
175
245
|
const list = readList();
|
|
176
|
-
const idx = list.findIndex((e) =>
|
|
177
|
-
if (
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
: -1;
|
|
188
|
-
|
|
189
|
-
if (target) {
|
|
190
|
-
// Existing address: refresh label, pin when newly proven, merge a duplicate identity into it.
|
|
246
|
+
const idx = list.findIndex((e) => holdsRoute(e, candidate));
|
|
247
|
+
if (heldBefore && idx < 0) return fail(reply, 409, "entry_removed");
|
|
248
|
+
|
|
249
|
+
if (idx >= 0) {
|
|
250
|
+
// A route already stored: refresh the label, pin when newly proven, fold a duplicate identity into it.
|
|
251
|
+
const target = list[idx];
|
|
252
|
+
if (target.fingerprint && proven && proven !== target.fingerprint) {
|
|
253
|
+
log(`[known-servers] route refused: different identity at ${routeUrl(candidate)} expected=${shortFp(target.fingerprint)} proven=${shortFp(proven)}`);
|
|
254
|
+
reply.code(409);
|
|
255
|
+
return { success: false, error: "identity_changed", expected: target.fingerprint, proven };
|
|
256
|
+
}
|
|
191
257
|
if (label) target.label = label;
|
|
192
258
|
if (proven && !target.fingerprint) {
|
|
193
259
|
target.fingerprint = proven;
|
|
194
|
-
|
|
195
|
-
const dropped = list.splice(holderIdx, 1)[0];
|
|
196
|
-
if (!target.label && dropped.label) target.label = dropped.label;
|
|
197
|
-
log(`[known-servers] merged duplicate identity: dropped ${dropped.host}:${dropped.port}`);
|
|
198
|
-
}
|
|
260
|
+
foldDuplicates(list, idx);
|
|
199
261
|
}
|
|
200
262
|
return persist(list, reply, false);
|
|
201
263
|
}
|
|
202
264
|
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
return
|
|
265
|
+
// A new route: it joins the entry that holds the proven identity (D1), else starts an entry.
|
|
266
|
+
const at = findAttachTarget(list, candidate, proven);
|
|
267
|
+
if (at >= 0 && proven) {
|
|
268
|
+
list[at].routes.push(candidate);
|
|
269
|
+
if (label) list[at].label = label;
|
|
270
|
+
const result = persist(list, reply, true);
|
|
271
|
+
if (result.success) log(`[known-servers] route attached fp=${shortFp(proven)} ${routeUrl(candidate)}`);
|
|
272
|
+
return result;
|
|
211
273
|
}
|
|
212
|
-
|
|
213
274
|
list.push({
|
|
214
275
|
host,
|
|
215
276
|
port,
|
|
216
277
|
...(label ? { label } : {}),
|
|
217
278
|
addedAt: new Date().toISOString(),
|
|
218
279
|
...(proven ? { fingerprint: proven } : {}),
|
|
280
|
+
routes: [candidate],
|
|
219
281
|
});
|
|
220
282
|
return persist(list, reply, false);
|
|
221
283
|
});
|
|
@@ -234,21 +296,39 @@ export function registerKnownServersRoutes(fastify: FastifyInstance, deps: Known
|
|
|
234
296
|
}
|
|
235
297
|
|
|
236
298
|
// ── Remove ───────────────────────────────────────────────────────────
|
|
299
|
+
// `{host, port, scheme?}` removes that route (and the entry with its last route);
|
|
300
|
+
// `{fingerprint}` removes every entry holding that identity. Idempotent.
|
|
237
301
|
fastify.delete<{ Body: RemoveKnownServerRequest }>(
|
|
238
302
|
"/api/known-servers",
|
|
239
303
|
{ preHandler: mutationGuard },
|
|
240
304
|
async (request, reply): Promise<ApiResponse> => {
|
|
241
|
-
const
|
|
242
|
-
if (
|
|
305
|
+
const body = (request.body ?? {}) as { host?: unknown; port?: unknown; scheme?: unknown; fingerprint?: unknown };
|
|
306
|
+
if (typeof body.fingerprint === "string" && body.fingerprint) {
|
|
307
|
+
const fingerprint = body.fingerprint;
|
|
308
|
+
return enqueueKnownServersWrite(() => {
|
|
309
|
+
const list = readList();
|
|
310
|
+
const kept = list.filter((e) => e.fingerprint !== fingerprint);
|
|
311
|
+
return kept.length === list.length ? { success: true as const } : persist(kept, reply, false);
|
|
312
|
+
});
|
|
313
|
+
}
|
|
314
|
+
const { host, port } = body;
|
|
315
|
+
if (!host || typeof host !== "string" || typeof port !== "number") {
|
|
243
316
|
return { success: false, error: "host and port are required" };
|
|
244
317
|
}
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
318
|
+
// No scheme names the address whatever its scheme (a pre-routes client sends none).
|
|
319
|
+
const scheme = body.scheme === undefined ? undefined : parseScheme(body.scheme);
|
|
320
|
+
if (scheme === null) return fail(reply, 400, "invalid_scheme");
|
|
321
|
+
return enqueueKnownServersWrite(() => {
|
|
322
|
+
const list = readList();
|
|
323
|
+
let changed = false;
|
|
324
|
+
const kept: KnownServer[] = [];
|
|
325
|
+
for (const e of list) {
|
|
326
|
+
const routes = e.routes.filter((r) => !(sameAddress(r, { host, port }) && (scheme === undefined || r.scheme === scheme)));
|
|
327
|
+
if (routes.length !== e.routes.length) changed = true;
|
|
328
|
+
if (routes.length > 0) kept.push({ ...e, routes });
|
|
329
|
+
}
|
|
330
|
+
return changed ? persist(kept, reply, false) : { success: true as const };
|
|
331
|
+
});
|
|
252
332
|
},
|
|
253
333
|
);
|
|
254
334
|
|
|
@@ -259,17 +339,21 @@ export function registerKnownServersRoutes(fastify: FastifyInstance, deps: Known
|
|
|
259
339
|
async (request, reply): Promise<ApiResponse> => {
|
|
260
340
|
const { host, port } = request.body ?? ({} as AcceptKnownServerMoveRequest);
|
|
261
341
|
if (!host || typeof port !== "number") return fail(reply, 400, "host and port are required");
|
|
342
|
+
// `host`/`port` name the entry's primary route (the mirror); only that route moves.
|
|
262
343
|
const entry = readList().find((e) => sameAddress(e, { host, port }));
|
|
263
344
|
const suggestion = entry && moves?.suggestionFor(entry);
|
|
264
345
|
if (!entry?.fingerprint || !suggestion) return fail(reply, 409, "no_suggestion");
|
|
265
346
|
const fingerprint = entry.fingerprint;
|
|
347
|
+
const primary = primaryRoute(entry.routes);
|
|
348
|
+
if (!primary) return fail(reply, 409, "no_suggestion");
|
|
266
349
|
|
|
267
|
-
// Re-verify BOTH halves before touching config
|
|
268
|
-
|
|
350
|
+
// Re-verify BOTH halves before touching config: the stored primary route in its own scheme,
|
|
351
|
+
// the suggested (mDNS, always http) address over http.
|
|
352
|
+
if (provedFingerprint(await prove(primary.host, primary.port, primary.scheme)) === fingerprint) {
|
|
269
353
|
moves?.withdraw(entry, "stored address answers again");
|
|
270
354
|
return fail(reply, 409, "stale_suggestion");
|
|
271
355
|
}
|
|
272
|
-
if (provedFingerprint(await prove(suggestion.host, suggestion.port)) !== fingerprint) {
|
|
356
|
+
if (provedFingerprint(await prove(suggestion.host, suggestion.port, "http")) !== fingerprint) {
|
|
273
357
|
return fail(reply, 409, "stale_suggestion");
|
|
274
358
|
}
|
|
275
359
|
|
|
@@ -277,7 +361,19 @@ export function registerKnownServersRoutes(fastify: FastifyInstance, deps: Known
|
|
|
277
361
|
const list = readList();
|
|
278
362
|
const idx = list.findIndex((e) => sameAddress(e, entry) && e.fingerprint === fingerprint);
|
|
279
363
|
if (idx < 0) return fail(reply, 409, "entry_removed");
|
|
280
|
-
|
|
364
|
+
const current = primaryRoute(list[idx].routes);
|
|
365
|
+
if (!current) return fail(reply, 409, "entry_removed");
|
|
366
|
+
const moved: Route = { host: suggestion.host, port: suggestion.port, scheme: "http", source: current.source };
|
|
367
|
+
// Only the primary route changes; a route that already holds the new address is not duplicated.
|
|
368
|
+
const seen = new Set<string>();
|
|
369
|
+
list[idx].routes = list[idx].routes
|
|
370
|
+
.map((r) => (r === current ? moved : r))
|
|
371
|
+
.filter((r) => {
|
|
372
|
+
const key = routeKey(r);
|
|
373
|
+
if (seen.has(key)) return false;
|
|
374
|
+
seen.add(key);
|
|
375
|
+
return true;
|
|
376
|
+
});
|
|
281
377
|
const result = persist(list, reply, false);
|
|
282
378
|
if (result.success) {
|
|
283
379
|
moves?.withdraw(entry, "accepted");
|
|
@@ -293,7 +389,8 @@ export function registerKnownServersRoutes(fastify: FastifyInstance, deps: Known
|
|
|
293
389
|
const lookup = deps.lookup ?? ((h: string) => dns.promises.lookup(h));
|
|
294
390
|
const doFetch = deps.fetchImpl ?? fetch;
|
|
295
391
|
|
|
296
|
-
|
|
392
|
+
/** Reachability of one stored route, over the route's own scheme (normal TLS verification, no redirects). */
|
|
393
|
+
async function probeOnce(host: string, port: number, scheme: RouteScheme): Promise<KnownServerProbeResult> {
|
|
297
394
|
const key = normalizeHostKey(host);
|
|
298
395
|
if (!net.isIP(key)) {
|
|
299
396
|
try {
|
|
@@ -307,7 +404,7 @@ export function registerKnownServersRoutes(fastify: FastifyInstance, deps: Known
|
|
|
307
404
|
}
|
|
308
405
|
}
|
|
309
406
|
try {
|
|
310
|
-
const res = await doFetch(
|
|
407
|
+
const res = await doFetch(`${routeUrl({ host, port, scheme })}/api/health`, {
|
|
311
408
|
redirect: "manual",
|
|
312
409
|
signal: AbortSignal.timeout(httpMs),
|
|
313
410
|
});
|
|
@@ -322,45 +419,46 @@ export function registerKnownServersRoutes(fastify: FastifyInstance, deps: Known
|
|
|
322
419
|
}
|
|
323
420
|
}
|
|
324
421
|
|
|
325
|
-
/** Pin the identity
|
|
326
|
-
async function backfill(
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
if (!proven) return;
|
|
422
|
+
/** Pin the identity a reachable route proved on its still-unpinned entry (folding a duplicate holder into it). */
|
|
423
|
+
async function backfill(route: Route, proven: string): Promise<void> {
|
|
424
|
+
// An entry whose address reaches this very server must never be pinned to this server's own identity.
|
|
425
|
+
if (proven === deps.ownFingerprint?.()) return;
|
|
330
426
|
await enqueueKnownServersWrite(() => {
|
|
331
427
|
const list = readList();
|
|
332
|
-
const idx = list.findIndex((e) =>
|
|
333
|
-
if (idx < 0 || list[idx].fingerprint) return;
|
|
428
|
+
const idx = list.findIndex((e) => holdsRoute(e, route));
|
|
429
|
+
if (idx < 0 || list[idx].fingerprint) return; // removed meanwhile (never recreated), or pinned meanwhile
|
|
334
430
|
list[idx].fingerprint = proven;
|
|
335
|
-
|
|
336
|
-
if (dup >= 0) {
|
|
337
|
-
const dropped = list.splice(dup, 1)[0];
|
|
338
|
-
if (!list.find((e) => e.fingerprint === proven)?.label && dropped.label) {
|
|
339
|
-
list[list.findIndex((e) => e.fingerprint === proven)].label = dropped.label;
|
|
340
|
-
}
|
|
341
|
-
log(`[known-servers] backfill merged duplicate identity: dropped ${dropped.host}:${dropped.port}`);
|
|
342
|
-
}
|
|
431
|
+
foldDuplicates(list, idx);
|
|
343
432
|
const result = writeList(list);
|
|
344
433
|
if (!result.success) log(`[known-servers] backfill write failed: ${result.error ?? "unknown"}`);
|
|
345
434
|
});
|
|
346
435
|
}
|
|
347
436
|
|
|
348
|
-
fastify.post<{ Body:
|
|
437
|
+
fastify.post<{ Body: KnownServerProbeRequest }>(
|
|
349
438
|
"/api/known-servers/probe",
|
|
350
439
|
{ preHandler: mutationGuard },
|
|
351
440
|
async (request, reply): Promise<ApiResponse<KnownServerProbeResult>> => {
|
|
352
|
-
const { host, port } = request.body ?? {};
|
|
441
|
+
const { host, port } = request.body ?? ({} as KnownServerProbeRequest);
|
|
353
442
|
if (typeof host !== "string" || typeof port !== "number") return fail(reply, 400, "host and port are required");
|
|
354
|
-
const
|
|
355
|
-
if (!
|
|
356
|
-
|
|
357
|
-
const
|
|
443
|
+
const scheme = parseScheme((request.body as { scheme?: unknown }).scheme);
|
|
444
|
+
if (!scheme) return fail(reply, 400, "invalid_scheme");
|
|
445
|
+
// SSRF guard: only a route that is still stored is ever contacted, in the stored spelling.
|
|
446
|
+
const route = readList()
|
|
447
|
+
.flatMap((e) => e.routes)
|
|
448
|
+
.find((r) => r.scheme === scheme && sameAddress(r, { host, port }));
|
|
449
|
+
if (!route) return fail(reply, 403, "not_a_known_server");
|
|
450
|
+
|
|
451
|
+
const key = routeKey(route);
|
|
358
452
|
let pending = probesInFlight.get(key);
|
|
359
453
|
if (!pending) {
|
|
360
|
-
pending = (async () => {
|
|
361
|
-
const result = await probeOnce(
|
|
362
|
-
if (result.status
|
|
363
|
-
|
|
454
|
+
pending = (async (): Promise<KnownServerProbeResult> => {
|
|
455
|
+
const result = await probeOnce(route.host, route.port, route.scheme);
|
|
456
|
+
if (result.status !== "reachable") return { ...result, scheme: route.scheme };
|
|
457
|
+
const proven = provedFingerprint(await prove(route.host, route.port, route.scheme));
|
|
458
|
+
if (!proven) return { ...result, scheme: route.scheme };
|
|
459
|
+
log(`[known-servers] probe proved fp=${shortFp(proven)} ${routeUrl(route)}`);
|
|
460
|
+
await backfill(route, proven).catch(() => {});
|
|
461
|
+
return { ...result, scheme: route.scheme, fingerprint: proven };
|
|
364
462
|
})().finally(() => probesInFlight.delete(key));
|
|
365
463
|
probesInFlight.set(key, pending);
|
|
366
464
|
}
|