@agent-deck/backend 1.11.8 → 2.0.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/dist/.tsbuildinfo +1 -1
- package/dist/audit/store.d.ts +43 -0
- package/dist/audit/store.d.ts.map +1 -0
- package/dist/audit/store.js +128 -0
- package/dist/audit/store.js.map +1 -0
- package/dist/auth/client-grants.d.ts +109 -0
- package/dist/auth/client-grants.d.ts.map +1 -0
- package/dist/auth/client-grants.js +260 -0
- package/dist/auth/client-grants.js.map +1 -0
- package/dist/auth/hosted-mode.d.ts +16 -0
- package/dist/auth/hosted-mode.d.ts.map +1 -0
- package/dist/auth/hosted-mode.js +136 -0
- package/dist/auth/hosted-mode.js.map +1 -0
- package/dist/auth/owner-auth.d.ts +24 -0
- package/dist/auth/owner-auth.d.ts.map +1 -0
- package/dist/auth/owner-auth.js +68 -0
- package/dist/auth/owner-auth.js.map +1 -0
- package/dist/auth/request-limiter.d.ts +17 -0
- package/dist/auth/request-limiter.d.ts.map +1 -0
- package/dist/auth/request-limiter.js +47 -0
- package/dist/auth/request-limiter.js.map +1 -0
- package/dist/cli-runtime.d.ts +2 -2
- package/dist/container-entrypoint.d.ts +2 -0
- package/dist/container-entrypoint.d.ts.map +1 -0
- package/dist/container-entrypoint.js +52 -0
- package/dist/container-entrypoint.js.map +1 -0
- package/dist/export-import/export-bundle.d.ts +2 -2
- package/dist/export-import/export-bundle.d.ts.map +1 -1
- package/dist/export-import/export-bundle.js +4 -2
- package/dist/export-import/export-bundle.js.map +1 -1
- package/dist/export-import/import-bundle.d.ts.map +1 -1
- package/dist/export-import/import-bundle.js +15 -3
- package/dist/export-import/import-bundle.js.map +1 -1
- package/dist/index.js +18 -15
- package/dist/index.js.map +1 -1
- package/dist/lib/destination-guard.d.ts +32 -0
- package/dist/lib/destination-guard.d.ts.map +1 -0
- package/dist/lib/destination-guard.js +238 -0
- package/dist/lib/destination-guard.js.map +1 -0
- package/dist/lib/fatal.d.ts +4 -4
- package/dist/lib/fatal.d.ts.map +1 -1
- package/dist/lib/fatal.js +36 -16
- package/dist/lib/fatal.js.map +1 -1
- package/dist/lib/graceful-shutdown.d.ts +26 -0
- package/dist/lib/graceful-shutdown.d.ts.map +1 -0
- package/dist/lib/graceful-shutdown.js +92 -0
- package/dist/lib/graceful-shutdown.js.map +1 -0
- package/dist/lib/mcp-oauth-discovery.d.ts.map +1 -1
- package/dist/lib/mcp-oauth-discovery.js +9 -4
- package/dist/lib/mcp-oauth-discovery.js.map +1 -1
- package/dist/lib/structured-console.d.ts +3 -0
- package/dist/lib/structured-console.d.ts.map +1 -0
- package/dist/lib/structured-console.js +29 -0
- package/dist/lib/structured-console.js.map +1 -0
- package/dist/mcp-index.js +2 -14
- package/dist/mcp-index.js.map +1 -1
- package/dist/mcp-server.d.ts +145 -2
- package/dist/mcp-server.d.ts.map +1 -1
- package/dist/mcp-server.js +524 -16
- package/dist/mcp-server.js.map +1 -1
- package/dist/mcp-session-binding.d.ts +54 -0
- package/dist/mcp-session-binding.d.ts.map +1 -1
- package/dist/mcp-session-binding.js +81 -0
- package/dist/mcp-session-binding.js.map +1 -1
- package/dist/mcp-tools/elicitation.d.ts +13 -4
- package/dist/mcp-tools/elicitation.d.ts.map +1 -1
- package/dist/mcp-tools/elicitation.js +34 -14
- package/dist/mcp-tools/elicitation.js.map +1 -1
- package/dist/mcp-tools/register.d.ts.map +1 -1
- package/dist/mcp-tools/register.js +105 -5
- package/dist/mcp-tools/register.js.map +1 -1
- package/dist/models/database.d.ts +12 -8
- package/dist/models/database.d.ts.map +1 -1
- package/dist/models/database.js +67 -51
- package/dist/models/database.js.map +1 -1
- package/dist/routes/agent-grants.d.ts +9 -0
- package/dist/routes/agent-grants.d.ts.map +1 -0
- package/dist/routes/agent-grants.js +97 -0
- package/dist/routes/agent-grants.js.map +1 -0
- package/dist/routes/audit.d.ts +5 -0
- package/dist/routes/audit.d.ts.map +1 -0
- package/dist/routes/audit.js +33 -0
- package/dist/routes/audit.js.map +1 -0
- package/dist/routes/decks.d.ts.map +1 -1
- package/dist/routes/decks.js +27 -0
- package/dist/routes/decks.js.map +1 -1
- package/dist/routes/mcp.d.ts.map +1 -1
- package/dist/routes/mcp.js +5 -4
- package/dist/routes/mcp.js.map +1 -1
- package/dist/routes/playbooks.d.ts.map +1 -1
- package/dist/routes/playbooks.js +9 -10
- package/dist/routes/playbooks.js.map +1 -1
- package/dist/routes/scope.d.ts.map +1 -1
- package/dist/routes/scope.js +4 -2
- package/dist/routes/scope.js.map +1 -1
- package/dist/routes/services.d.ts.map +1 -1
- package/dist/routes/services.js +6 -0
- package/dist/routes/services.js.map +1 -1
- package/dist/routes/trusted-session.d.ts +2 -0
- package/dist/routes/trusted-session.d.ts.map +1 -1
- package/dist/routes/trusted-session.js +194 -1
- package/dist/routes/trusted-session.js.map +1 -1
- package/dist/routes/usage.d.ts +3 -1
- package/dist/routes/usage.d.ts.map +1 -1
- package/dist/routes/usage.js +20 -1
- package/dist/routes/usage.js.map +1 -1
- package/dist/scope/live-display-registry.d.ts +56 -1
- package/dist/scope/live-display-registry.d.ts.map +1 -1
- package/dist/scope/live-display-registry.js +115 -2
- package/dist/scope/live-display-registry.js.map +1 -1
- package/dist/server/cors-origins.d.ts +6 -0
- package/dist/server/cors-origins.d.ts.map +1 -0
- package/dist/server/cors-origins.js +122 -0
- package/dist/server/cors-origins.js.map +1 -0
- package/dist/server/degraded.d.ts +15 -0
- package/dist/server/degraded.d.ts.map +1 -0
- package/dist/server/degraded.js +55 -0
- package/dist/server/degraded.js.map +1 -0
- package/dist/server/graceful-shutdown.fixture.d.ts +2 -0
- package/dist/server/graceful-shutdown.fixture.d.ts.map +1 -0
- package/dist/server/graceful-shutdown.fixture.js +52 -0
- package/dist/server/graceful-shutdown.fixture.js.map +1 -0
- package/dist/server/health.d.ts +21 -0
- package/dist/server/health.d.ts.map +1 -0
- package/dist/server/health.js +65 -0
- package/dist/server/health.js.map +1 -0
- package/dist/server/index.d.ts +2 -0
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +60 -26
- package/dist/server/index.js.map +1 -1
- package/dist/services/icon-resolver.d.ts.map +1 -1
- package/dist/services/icon-resolver.js +2 -1
- package/dist/services/icon-resolver.js.map +1 -1
- package/dist/services/mcp-client-manager.d.ts.map +1 -1
- package/dist/services/mcp-client-manager.js +3 -0
- package/dist/services/mcp-client-manager.js.map +1 -1
- package/dist/services/mcp-discovery-service.d.ts.map +1 -1
- package/dist/services/mcp-discovery-service.js +2 -1
- package/dist/services/mcp-discovery-service.js.map +1 -1
- package/dist/services/oauth-manager.d.ts.map +1 -1
- package/dist/services/oauth-manager.js +12 -7
- package/dist/services/oauth-manager.js.map +1 -1
- package/dist/services/service-manager.d.ts.map +1 -1
- package/dist/services/service-manager.js +15 -4
- package/dist/services/service-manager.js.map +1 -1
- package/dist/store/atomic-write.d.ts.map +1 -1
- package/dist/store/atomic-write.js +44 -3
- package/dist/store/atomic-write.js.map +1 -1
- package/dist/store/deck-codec.d.ts +9 -0
- package/dist/store/deck-codec.d.ts.map +1 -1
- package/dist/store/deck-codec.js +64 -1
- package/dist/store/deck-codec.js.map +1 -1
- package/dist/store/deck-file.d.ts +3 -3
- package/dist/store/deck-file.d.ts.map +1 -1
- package/dist/store/deck-file.js +4 -3
- package/dist/store/deck-file.js.map +1 -1
- package/dist/store/index.d.ts +1 -0
- package/dist/store/index.d.ts.map +1 -1
- package/dist/store/index.js +1 -0
- package/dist/store/index.js.map +1 -1
- package/dist/store/migrate-v1-to-v2.d.ts +22 -0
- package/dist/store/migrate-v1-to-v2.d.ts.map +1 -0
- package/dist/store/migrate-v1-to-v2.js +167 -0
- package/dist/store/migrate-v1-to-v2.js.map +1 -0
- package/dist/store/migrate.js +2 -2
- package/dist/store/migrate.js.map +1 -1
- package/dist/store/reindex.d.ts.map +1 -1
- package/dist/store/reindex.js +16 -6
- package/dist/store/reindex.js.map +1 -1
- package/dist/store/startup.d.ts.map +1 -1
- package/dist/store/startup.js +13 -0
- package/dist/store/startup.js.map +1 -1
- package/dist/store/writer.d.ts.map +1 -1
- package/dist/store/writer.js +7 -3
- package/dist/store/writer.js.map +1 -1
- package/dist/trusted-session/route-policy-registry.d.ts.map +1 -1
- package/dist/trusted-session/route-policy-registry.js +12 -1
- package/dist/trusted-session/route-policy-registry.js.map +1 -1
- package/dist/trusted-session/store.d.ts +37 -2
- package/dist/trusted-session/store.d.ts.map +1 -1
- package/dist/trusted-session/store.js +75 -20
- package/dist/trusted-session/store.js.map +1 -1
- package/dist/vault/encrypted-file-secret-store.d.ts +61 -0
- package/dist/vault/encrypted-file-secret-store.d.ts.map +1 -0
- package/dist/vault/encrypted-file-secret-store.js +211 -0
- package/dist/vault/encrypted-file-secret-store.js.map +1 -0
- package/dist/vault/index.d.ts +1 -0
- package/dist/vault/index.d.ts.map +1 -1
- package/dist/vault/index.js +1 -0
- package/dist/vault/index.js.map +1 -1
- package/dist/vault/secret-store.d.ts +8 -0
- package/dist/vault/secret-store.d.ts.map +1 -1
- package/dist/vault/secret-store.js +31 -2
- package/dist/vault/secret-store.js.map +1 -1
- package/package.json +2 -2
- package/static-ui/assets/index-ClYpYc1K.js +251 -0
- package/static-ui/assets/index-DMqzTrRe.css +1 -0
- package/static-ui/index.html +2 -2
- package/static-ui/assets/index-CQf3Vouc.css +0 -1
- package/static-ui/assets/index-DCImqPRz.js +0 -235
package/dist/mcp-server.js
CHANGED
|
@@ -3,14 +3,20 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.AgentDeckMCPServer = void 0;
|
|
6
|
+
exports.AgentDeckMCPServer = exports.LIVE_TOUCH_KEEPALIVE_ENV_VAR = exports.DEFAULT_LIVE_TOUCH_KEEPALIVE_MS = exports.MCP_INITIALIZE_RATE_WINDOW_MS = exports.MCP_INITIALIZE_RATE_LIMIT = exports.MCP_REQUIRE_BEARER_ENV_VAR = void 0;
|
|
7
|
+
exports.isBearerGrantRequired = isBearerGrantRequired;
|
|
8
|
+
exports.resolveLiveTouchKeepAliveMs = resolveLiveTouchKeepAliveMs;
|
|
7
9
|
const mcp_js_1 = require("@modelcontextprotocol/sdk/server/mcp.js");
|
|
8
10
|
const streamableHttp_js_1 = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
|
|
9
11
|
const types_js_1 = require("@modelcontextprotocol/sdk/types.js");
|
|
10
12
|
const shared_1 = require("@agent-deck/shared");
|
|
11
13
|
const express_1 = __importDefault(require("express"));
|
|
12
14
|
const node_crypto_1 = require("node:crypto");
|
|
15
|
+
const better_sqlite3_1 = __importDefault(require("better-sqlite3"));
|
|
13
16
|
const version_1 = require("./lib/version");
|
|
17
|
+
const paths_1 = require("./lib/paths");
|
|
18
|
+
const live_display_registry_1 = require("./scope/live-display-registry");
|
|
19
|
+
const client_grants_1 = require("./auth/client-grants");
|
|
14
20
|
const backend_api_error_1 = require("./lib/backend-api-error");
|
|
15
21
|
const policy_1 = require("./mcp-tools/policy");
|
|
16
22
|
const mcp_session_binding_1 = require("./mcp-session-binding");
|
|
@@ -19,6 +25,8 @@ const elicitation_1 = require("./mcp-tools/elicitation");
|
|
|
19
25
|
const profile_1 = require("./mcp-tools/profile");
|
|
20
26
|
const mcp_unassigned_1 = require("./mcp-unassigned");
|
|
21
27
|
const stub_sync_1 = require("./playbooks/stub-sync");
|
|
28
|
+
const request_limiter_1 = require("./auth/request-limiter");
|
|
29
|
+
const store_1 = require("./audit/store");
|
|
22
30
|
function readWorkspaceRootHeader(req) {
|
|
23
31
|
const raw = req.headers[shared_1.AGENT_DECK_WORKSPACE_HEADER];
|
|
24
32
|
const value = typeof raw === 'string' ? raw.trim() : '';
|
|
@@ -29,6 +37,72 @@ function readLaunchDeckHeader(req) {
|
|
|
29
37
|
const value = typeof raw === 'string' ? raw.trim() : '';
|
|
30
38
|
return value || undefined;
|
|
31
39
|
}
|
|
40
|
+
/**
|
|
41
|
+
* Opaque run-correlation id for launch-selected sessions (NOT-304).
|
|
42
|
+
* Returned unvalidated — the binding store normalizes and adopt-once
|
|
43
|
+
* semantics keep it observability-only: it can never select a deck, grant
|
|
44
|
+
* access, change mode, or participate in authorization.
|
|
45
|
+
*/
|
|
46
|
+
function readCorrelationIdHeader(req) {
|
|
47
|
+
const raw = req.headers[shared_1.AGENT_DECK_CORRELATION_HEADER];
|
|
48
|
+
const value = typeof raw === 'string' ? raw.trim() : '';
|
|
49
|
+
return value || undefined;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* NOT-318: hosted-mode flag. When `AGENT_DECK_MCP_REQUIRE_BEARER=1`, every
|
|
53
|
+
* `/mcp` request requires a valid per-agent grant secret, regardless of
|
|
54
|
+
* peer address. Peer-address detection is explicitly rejected as the
|
|
55
|
+
* trigger (TLS-terminating proxies forward internet traffic over
|
|
56
|
+
* loopback), and `X-Forwarded-*` headers are never trusted for auth.
|
|
57
|
+
* The local launcher never sets this flag, so loopback sessions stay
|
|
58
|
+
* bearer-free with zero config change.
|
|
59
|
+
*/
|
|
60
|
+
exports.MCP_REQUIRE_BEARER_ENV_VAR = 'AGENT_DECK_MCP_REQUIRE_BEARER';
|
|
61
|
+
exports.MCP_INITIALIZE_RATE_LIMIT = 30;
|
|
62
|
+
exports.MCP_INITIALIZE_RATE_WINDOW_MS = 60_000;
|
|
63
|
+
function isBearerGrantRequired(raw = process.env[exports.MCP_REQUIRE_BEARER_ENV_VAR]) {
|
|
64
|
+
return raw === '1' || raw?.trim().toLowerCase() === 'true';
|
|
65
|
+
}
|
|
66
|
+
/** Extract the bearer secret without ever logging or echoing it. */
|
|
67
|
+
function readBearerToken(req) {
|
|
68
|
+
const header = req.headers.authorization;
|
|
69
|
+
if (typeof header !== 'string') {
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
const match = /^Bearer (.+)$/.exec(header.trim());
|
|
73
|
+
const token = match?.[1]?.trim();
|
|
74
|
+
return token || null;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* NOT-309: keep-alive touch cadence for idle-but-connected MCP sessions.
|
|
78
|
+
* Every MCP tool call already bumps `lastActivityAt` (debounced POST touch),
|
|
79
|
+
* but a session with an open transport and no tool calls sends no HTTP POSTs
|
|
80
|
+
* (the SSE stream is a GET), so without a keep-alive it would expire out of
|
|
81
|
+
* the live-display registry while still connected. Override via
|
|
82
|
+
* `AGENT_DECK_MCP_LIVE_TOUCH_KEEPALIVE_MS` (`0` disables); the default is
|
|
83
|
+
* also clamped under a third of the stale bound so a shortened
|
|
84
|
+
* `LIVE_DISPLAY_STALE_MS` never outruns it.
|
|
85
|
+
*
|
|
86
|
+
* Both processes must see the same `LIVE_DISPLAY_STALE_MS`: the MCP server
|
|
87
|
+
* runs separately (mcp-index) and resolves the bound from its own
|
|
88
|
+
* environment, so shortening it only on the backend leaves the keep-alive
|
|
89
|
+
* at 5 minutes and idle sessions expire. Export it for both processes.
|
|
90
|
+
*/
|
|
91
|
+
exports.DEFAULT_LIVE_TOUCH_KEEPALIVE_MS = 5 * 60_000;
|
|
92
|
+
exports.LIVE_TOUCH_KEEPALIVE_ENV_VAR = 'AGENT_DECK_MCP_LIVE_TOUCH_KEEPALIVE_MS';
|
|
93
|
+
function resolveLiveTouchKeepAliveMs(raw, staleMs) {
|
|
94
|
+
const fallback = staleMs > 0
|
|
95
|
+
? Math.max(1, Math.min(exports.DEFAULT_LIVE_TOUCH_KEEPALIVE_MS, Math.floor(staleMs / 3)))
|
|
96
|
+
: exports.DEFAULT_LIVE_TOUCH_KEEPALIVE_MS;
|
|
97
|
+
if (raw === undefined || raw.trim() === '') {
|
|
98
|
+
return fallback;
|
|
99
|
+
}
|
|
100
|
+
const parsed = Number(raw.trim());
|
|
101
|
+
if (!Number.isFinite(parsed) || parsed < 0) {
|
|
102
|
+
return fallback;
|
|
103
|
+
}
|
|
104
|
+
return Math.floor(parsed);
|
|
105
|
+
}
|
|
32
106
|
class AgentDeckMCPServer {
|
|
33
107
|
/** Cap on remembered stale session ids — the tally is diagnostics, not a ledger. */
|
|
34
108
|
static STALE_SESSION_SAMPLE_LIMIT = 200;
|
|
@@ -46,6 +120,8 @@ class AgentDeckMCPServer {
|
|
|
46
120
|
/** Session badge from the backend registry (POST /api/scope/live-display response). */
|
|
47
121
|
badgeBySession = new Map();
|
|
48
122
|
lastTouchAtMs = new Map();
|
|
123
|
+
/** NOT-309: keep-alive timer proving idle-but-connected sessions still live. */
|
|
124
|
+
liveTouchKeepAliveTimer = null;
|
|
49
125
|
/** In-flight live-display unregisters so `stop()` can drain them before closing. */
|
|
50
126
|
unregisterTasks = new Map();
|
|
51
127
|
/** Changes on every process start — how a client detects it outlived the server. */
|
|
@@ -70,19 +146,86 @@ class AgentDeckMCPServer {
|
|
|
70
146
|
}
|
|
71
147
|
return this.mcpServerForRegistration;
|
|
72
148
|
}
|
|
73
|
-
|
|
149
|
+
/** Injected grant store (tests). `undefined` means "resolve lazily". */
|
|
150
|
+
grantStoreOverride;
|
|
151
|
+
/** Lazily opened grant store for hosted mode (shared backend database file). */
|
|
152
|
+
grantStoreCache = null;
|
|
153
|
+
auditStoreOverride;
|
|
154
|
+
auditStoreCache = null;
|
|
155
|
+
sharedSecurityDb = null;
|
|
156
|
+
initializeLimiter;
|
|
157
|
+
constructor(port = 3001, backendUrl = 'http://localhost:8000', toolProfile, host = '127.0.0.1', options) {
|
|
74
158
|
this.port = port;
|
|
75
159
|
this.backendUrl = backendUrl;
|
|
76
160
|
this.toolProfile = toolProfile ?? (0, profile_1.resolveMcpToolProfile)();
|
|
77
161
|
this.host = host;
|
|
162
|
+
this.grantStoreOverride = options?.grantStore;
|
|
163
|
+
this.auditStoreOverride = options?.auditStore;
|
|
164
|
+
this.initializeLimiter = new request_limiter_1.RequestLimiter(exports.MCP_INITIALIZE_RATE_WINDOW_MS, options?.now);
|
|
78
165
|
this.app = (0, express_1.default)();
|
|
79
|
-
this.app.use(
|
|
166
|
+
this.app.use(process.env.AGENT_DECK_HOSTED_MODE === '1'
|
|
167
|
+
? express_1.default.json({ limit: 1024 * 1024 })
|
|
168
|
+
: express_1.default.json());
|
|
80
169
|
this.setupRoutes();
|
|
81
170
|
this.sessionBinding = new mcp_session_binding_1.McpSessionBindingStore({
|
|
82
171
|
workspace: process.env.AGENT_DECK_WORKSPACE,
|
|
83
172
|
deckId: process.env.AGENT_DECK_DECK_ID,
|
|
84
173
|
});
|
|
85
174
|
}
|
|
175
|
+
/**
|
|
176
|
+
* NOT-318: grant metadata store. An injected store (tests) wins; otherwise
|
|
177
|
+
* the shared backend database file is opened lazily — only when a bearer
|
|
178
|
+
* is presented or hosted mode requires one, so loopback-only processes
|
|
179
|
+
* and existing tests never touch the database file.
|
|
180
|
+
*/
|
|
181
|
+
getGrantStore() {
|
|
182
|
+
if (this.grantStoreOverride !== undefined) {
|
|
183
|
+
return this.grantStoreOverride;
|
|
184
|
+
}
|
|
185
|
+
if (this.grantStoreCache) {
|
|
186
|
+
return this.grantStoreCache;
|
|
187
|
+
}
|
|
188
|
+
try {
|
|
189
|
+
const dbPath = process.env.AGENT_DECK_DB_PATH?.trim() || (0, paths_1.resolveDatabasePath)();
|
|
190
|
+
this.sharedSecurityDb ??= new better_sqlite3_1.default(dbPath);
|
|
191
|
+
this.grantStoreCache = new client_grants_1.ClientGrantStore(this.sharedSecurityDb);
|
|
192
|
+
return this.grantStoreCache;
|
|
193
|
+
}
|
|
194
|
+
catch {
|
|
195
|
+
return null;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
getAuditStore() {
|
|
199
|
+
if (this.auditStoreOverride !== undefined)
|
|
200
|
+
return this.auditStoreOverride;
|
|
201
|
+
if (this.auditStoreCache)
|
|
202
|
+
return this.auditStoreCache;
|
|
203
|
+
try {
|
|
204
|
+
const dbPath = process.env.AGENT_DECK_DB_PATH?.trim() || (0, paths_1.resolveDatabasePath)();
|
|
205
|
+
this.sharedSecurityDb ??= new better_sqlite3_1.default(dbPath);
|
|
206
|
+
this.auditStoreCache = new store_1.AuditStore(this.sharedSecurityDb);
|
|
207
|
+
return this.auditStoreCache;
|
|
208
|
+
}
|
|
209
|
+
catch {
|
|
210
|
+
return null;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* NOT-318: authenticate one bearer token to a grant principal. Every
|
|
215
|
+
* failure mode (missing store, malformed, unknown id, secret mismatch,
|
|
216
|
+
* expired, revoked) returns null — the caller answers one uniform 401
|
|
217
|
+
* with no oracle. Touches `lastUsedAt`; never logs or returns the secret.
|
|
218
|
+
*/
|
|
219
|
+
authenticateGrant(token) {
|
|
220
|
+
if (!token) {
|
|
221
|
+
return null;
|
|
222
|
+
}
|
|
223
|
+
const store = this.getGrantStore();
|
|
224
|
+
if (!store) {
|
|
225
|
+
return null;
|
|
226
|
+
}
|
|
227
|
+
return store.authenticateToken(token);
|
|
228
|
+
}
|
|
86
229
|
/** Actual listening port (resolves OS-assigned `port: 0` after `start()`). */
|
|
87
230
|
getPort() {
|
|
88
231
|
return this.port;
|
|
@@ -91,12 +234,19 @@ class AgentDeckMCPServer {
|
|
|
91
234
|
* One McpServer per transport session. Tools/resources close over `sessionId`
|
|
92
235
|
* so concurrent requests cannot steal another session's backend authority.
|
|
93
236
|
*/
|
|
94
|
-
createMcpServer(sessionId) {
|
|
237
|
+
async createMcpServer(sessionId) {
|
|
95
238
|
const unassigned = this.sessionBinding.isUnassigned(sessionId);
|
|
239
|
+
let instructions;
|
|
240
|
+
if (unassigned) {
|
|
241
|
+
instructions = mcp_unassigned_1.UNASSIGNED_DECK_MESSAGE;
|
|
242
|
+
}
|
|
243
|
+
else {
|
|
244
|
+
instructions = await this.resolveInitializeInstructions(sessionId);
|
|
245
|
+
}
|
|
96
246
|
this.mcpServerForRegistration = new mcp_js_1.McpServer({
|
|
97
247
|
name: "agent-deck-server",
|
|
98
248
|
version: (0, version_1.getAgentDeckVersion)(),
|
|
99
|
-
},
|
|
249
|
+
}, instructions ? { instructions } : undefined);
|
|
100
250
|
this.setupTools(sessionId);
|
|
101
251
|
if (!unassigned) {
|
|
102
252
|
this.setupResources(sessionId);
|
|
@@ -105,6 +255,30 @@ class AgentDeckMCPServer {
|
|
|
105
255
|
this.mcpServerForRegistration = undefined;
|
|
106
256
|
return server;
|
|
107
257
|
}
|
|
258
|
+
/**
|
|
259
|
+
* NOT-375: initialize-time server instructions for an assigned deck.
|
|
260
|
+
* The bound deck's non-empty operating instructions ride the initialize
|
|
261
|
+
* response as a bootstrap hint where the SDK/host surfaces them; empty
|
|
262
|
+
* instructions omit the field. This value is frozen at connect time and
|
|
263
|
+
* never updates after a hot deck switch — `get_session_context` is the
|
|
264
|
+
* authoritative live read. Any failure here falls back to no instructions
|
|
265
|
+
* rather than failing the handshake; the bootstrap tool call surfaces the
|
|
266
|
+
* underlying deck error instead.
|
|
267
|
+
*/
|
|
268
|
+
async resolveInitializeInstructions(sessionId) {
|
|
269
|
+
const binding = this.sessionBinding.getBinding(sessionId);
|
|
270
|
+
if (!binding.deckId && !binding.runtimeSessionId) {
|
|
271
|
+
return undefined;
|
|
272
|
+
}
|
|
273
|
+
try {
|
|
274
|
+
const deck = await this.callBackendAPI('/api/scope/deck', {}, sessionId);
|
|
275
|
+
const value = deck?.operatingInstructions;
|
|
276
|
+
return typeof value === 'string' && value.length > 0 ? value : undefined;
|
|
277
|
+
}
|
|
278
|
+
catch {
|
|
279
|
+
return undefined;
|
|
280
|
+
}
|
|
281
|
+
}
|
|
108
282
|
async fetchDeck(deckId, sessionId) {
|
|
109
283
|
const deck = await fetch(`${this.backendUrl}/api/decks/${deckId}`, {
|
|
110
284
|
headers: this.sessionBinding.getAgentHeaders(sessionId),
|
|
@@ -162,13 +336,26 @@ class AgentDeckMCPServer {
|
|
|
162
336
|
}
|
|
163
337
|
}
|
|
164
338
|
static TOUCH_DEBOUNCE_MS = 5_000;
|
|
165
|
-
/**
|
|
166
|
-
|
|
339
|
+
/**
|
|
340
|
+
* Fire-and-forget lastActivityAt bump; only for sessions this process
|
|
341
|
+
* registered (badge-holding). `force` bypasses the per-request debounce —
|
|
342
|
+
* the keep-alive already runs on a minutes-long cadence, so debouncing it
|
|
343
|
+
* would only delay proof of life.
|
|
344
|
+
*
|
|
345
|
+
* NOT-309 repair round 2: when the backend reports `found: false` the
|
|
346
|
+
* entry was swept while this transport stayed open (host sleep longer
|
|
347
|
+
* than the stale bound, then a status-line read on wake). Re-register so
|
|
348
|
+
* the live session returns to the status line without a reconnect. An
|
|
349
|
+
* explicit `found === false` is required — older backends answer `{}` and
|
|
350
|
+
* must not trigger a re-register storm.
|
|
351
|
+
*/
|
|
352
|
+
touchLiveDisplay(sessionId, force = false) {
|
|
167
353
|
if (!this.badgeBySession.has(sessionId)) {
|
|
168
354
|
return;
|
|
169
355
|
}
|
|
170
356
|
const now = Date.now();
|
|
171
|
-
if (
|
|
357
|
+
if (!force &&
|
|
358
|
+
now - (this.lastTouchAtMs.get(sessionId) ?? 0) < AgentDeckMCPServer.TOUCH_DEBOUNCE_MS) {
|
|
172
359
|
return;
|
|
173
360
|
}
|
|
174
361
|
this.lastTouchAtMs.set(sessionId, now);
|
|
@@ -176,7 +363,17 @@ class AgentDeckMCPServer {
|
|
|
176
363
|
method: 'POST',
|
|
177
364
|
headers: { 'Content-Type': 'application/json' },
|
|
178
365
|
body: JSON.stringify({ at: new Date().toISOString() }),
|
|
179
|
-
}, sessionId)
|
|
366
|
+
}, sessionId)
|
|
367
|
+
.then((result) => {
|
|
368
|
+
// Guard against the close race: a keep-alive touch in flight when
|
|
369
|
+
// transport.onclose sends DELETE answers found:false after the entry
|
|
370
|
+
// is gone. Re-registering then would resurrect a closed session, so
|
|
371
|
+
// only re-register while the transport is still open.
|
|
372
|
+
if (result && result.found === false && this.sessions.has(sessionId)) {
|
|
373
|
+
void this.registerLiveDisplay(sessionId).catch(() => { });
|
|
374
|
+
}
|
|
375
|
+
})
|
|
376
|
+
.catch(() => { });
|
|
180
377
|
}
|
|
181
378
|
static UNREGISTER_TIMEOUT_MS = 3_000;
|
|
182
379
|
/** Override via AGENT_DECK_MCP_UNREGISTER_TIMEOUT_MS (tests use a short value). */
|
|
@@ -190,6 +387,36 @@ class AgentDeckMCPServer {
|
|
|
190
387
|
? parsed
|
|
191
388
|
: AgentDeckMCPServer.UNREGISTER_TIMEOUT_MS;
|
|
192
389
|
}
|
|
390
|
+
/**
|
|
391
|
+
* NOT-309: keep the registry fresh for sessions with an open transport but
|
|
392
|
+
* no tool calls. Only badge-holding (registered) sessions are touched; the
|
|
393
|
+
* backend ignores touches for sessions it never saw, so unassigned or
|
|
394
|
+
* half-initialized sessions are harmless no-ops by construction.
|
|
395
|
+
*/
|
|
396
|
+
touchAllLiveDisplays() {
|
|
397
|
+
for (const sessionId of this.sessions.keys()) {
|
|
398
|
+
this.touchLiveDisplay(sessionId, true);
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
startLiveDisplayKeepAlive() {
|
|
402
|
+
this.stopLiveDisplayKeepAlive();
|
|
403
|
+
const staleMs = (0, live_display_registry_1.resolveLiveDisplayStaleMs)(process.env.LIVE_DISPLAY_STALE_MS);
|
|
404
|
+
const intervalMs = resolveLiveTouchKeepAliveMs(process.env[exports.LIVE_TOUCH_KEEPALIVE_ENV_VAR], staleMs);
|
|
405
|
+
if (intervalMs <= 0) {
|
|
406
|
+
return;
|
|
407
|
+
}
|
|
408
|
+
const timer = setInterval(() => {
|
|
409
|
+
this.touchAllLiveDisplays();
|
|
410
|
+
}, intervalMs);
|
|
411
|
+
timer.unref?.();
|
|
412
|
+
this.liveTouchKeepAliveTimer = timer;
|
|
413
|
+
}
|
|
414
|
+
stopLiveDisplayKeepAlive() {
|
|
415
|
+
if (this.liveTouchKeepAliveTimer) {
|
|
416
|
+
clearInterval(this.liveTouchKeepAliveTimer);
|
|
417
|
+
this.liveTouchKeepAliveTimer = null;
|
|
418
|
+
}
|
|
419
|
+
}
|
|
193
420
|
async unregisterLiveDisplay(sessionId) {
|
|
194
421
|
const controller = new AbortController();
|
|
195
422
|
const timer = setTimeout(() => controller.abort(), AgentDeckMCPServer.unregisterTimeoutMs());
|
|
@@ -696,6 +923,134 @@ class AgentDeckMCPServer {
|
|
|
696
923
|
id: null,
|
|
697
924
|
});
|
|
698
925
|
}
|
|
926
|
+
/**
|
|
927
|
+
* NOT-318: the single 401 envelope for every credential failure on a
|
|
928
|
+
* hosted endpoint (missing / malformed / invalid / expired / revoked).
|
|
929
|
+
* Byte-identical every time — including the constant `WWW-Authenticate:
|
|
930
|
+
* Bearer` challenge — so probers learn nothing, and generic HTTP
|
|
931
|
+
* clients stay well-behaved. Never carries grant state or deck detail.
|
|
932
|
+
*/
|
|
933
|
+
sendGrantRequired(res) {
|
|
934
|
+
res.status(401).set('WWW-Authenticate', 'Bearer').json({
|
|
935
|
+
jsonrpc: '2.0',
|
|
936
|
+
error: { code: -32001, message: 'GRANT_REQUIRED' },
|
|
937
|
+
id: null,
|
|
938
|
+
});
|
|
939
|
+
}
|
|
940
|
+
/**
|
|
941
|
+
* NOT-318: authenticated but outside the grant allowlist. Only reachable
|
|
942
|
+
* post-auth, so it oracles the allowlist solely to the already-
|
|
943
|
+
* authenticated owner. Transport kept.
|
|
944
|
+
*/
|
|
945
|
+
sendOutOfScope(res) {
|
|
946
|
+
res.status(403).json({
|
|
947
|
+
jsonrpc: '2.0',
|
|
948
|
+
error: { code: -32001, message: 'RESOURCE_OUT_OF_SCOPE' },
|
|
949
|
+
id: null,
|
|
950
|
+
});
|
|
951
|
+
}
|
|
952
|
+
/**
|
|
953
|
+
* NOT-318: bind a fresh MCP session to an authenticated grant principal.
|
|
954
|
+
* Mirrors `authenticateLaunchDeck` (workspace + correlation handling) but
|
|
955
|
+
* resolves through the grant: the deck was already constrained by
|
|
956
|
+
* `resolveGrantDeck`, and the owning grant id is linked on the runtime
|
|
957
|
+
* session so deck-switch creation/approval enforces the same allowlist.
|
|
958
|
+
*/
|
|
959
|
+
async authenticateGrantDeck(sessionId, req, principal, deckId) {
|
|
960
|
+
const response = await fetch(`${this.backendUrl}/api/trusted-session/mcp/connect-deck`, {
|
|
961
|
+
method: 'POST',
|
|
962
|
+
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
|
963
|
+
body: JSON.stringify({
|
|
964
|
+
deckId,
|
|
965
|
+
mcpSessionId: sessionId,
|
|
966
|
+
grantId: principal.grantId,
|
|
967
|
+
}),
|
|
968
|
+
});
|
|
969
|
+
const body = (await response.json());
|
|
970
|
+
if (!response.ok || !body.success || !body.data) {
|
|
971
|
+
throw new Error(body.error ?? 'GRANT_DECK_INVALID');
|
|
972
|
+
}
|
|
973
|
+
const existing = this.sessionBinding.getBinding(sessionId);
|
|
974
|
+
const workspaceRoot = readWorkspaceRootHeader(req) ??
|
|
975
|
+
existing.workspaceRoot ??
|
|
976
|
+
(process.env.AGENT_DECK_WORKSPACE?.trim() || undefined);
|
|
977
|
+
this.sessionBinding.setGrantSession(sessionId, {
|
|
978
|
+
grantId: principal.grantId,
|
|
979
|
+
label: principal.label,
|
|
980
|
+
defaultDeck: principal.defaultDeck,
|
|
981
|
+
allowedDecks: principal.allowedDecks,
|
|
982
|
+
runtimeSessionId: body.data.sessionId,
|
|
983
|
+
deckId: body.data.deckId,
|
|
984
|
+
workspaceRoot,
|
|
985
|
+
mode: body.data.mode,
|
|
986
|
+
});
|
|
987
|
+
const correlationId = readCorrelationIdHeader(req);
|
|
988
|
+
if (correlationId) {
|
|
989
|
+
this.sessionBinding.setCorrelationId(sessionId, correlationId);
|
|
990
|
+
}
|
|
991
|
+
}
|
|
992
|
+
/**
|
|
993
|
+
* NOT-318: revalidate a grant-bound session on every follow-up request.
|
|
994
|
+
* The grant (not a cached decision) is re-resolved per request, so
|
|
995
|
+
* revocation and expiry fail the *next* request closed — no grace
|
|
996
|
+
* window, strictly inside the 60s bound. The deck header is
|
|
997
|
+
* request-only: a header outside the allowlist is denied with 403 and
|
|
998
|
+
* the binding is left untouched; a header for another allowed deck is
|
|
999
|
+
* ignored (deck changes go through human-approved switch_deck, which
|
|
1000
|
+
* re-checks the same allowlist). Transport kept on every denial so a
|
|
1001
|
+
* correct credential on the next attempt can succeed.
|
|
1002
|
+
*/
|
|
1003
|
+
async requireGrantFollowUp(sessionId, req, res) {
|
|
1004
|
+
const scope = this.sessionBinding.getGrantScope(sessionId);
|
|
1005
|
+
if (!scope) {
|
|
1006
|
+
this.sendGrantRequired(res);
|
|
1007
|
+
return false;
|
|
1008
|
+
}
|
|
1009
|
+
const principal = this.authenticateGrant(readBearerToken(req));
|
|
1010
|
+
if (!principal || principal.grantId !== scope.grantId) {
|
|
1011
|
+
const presented = (0, client_grants_1.parseGrantToken)(readBearerToken(req) ?? '');
|
|
1012
|
+
console.warn('[agent-deck] Grant follow-up auth failed (transport kept):', `grantId=${presented?.grantId ?? 'none'}`);
|
|
1013
|
+
this.sendGrantRequired(res);
|
|
1014
|
+
return false;
|
|
1015
|
+
}
|
|
1016
|
+
// Renew the backend lease and pick up post-approval deck/mode moves,
|
|
1017
|
+
// mirroring the launch follow-up refresh. A backend-revoked session
|
|
1018
|
+
// (grant revoked via the owner API) fails closed here as well.
|
|
1019
|
+
try {
|
|
1020
|
+
await this.refreshRuntimeSession(sessionId);
|
|
1021
|
+
}
|
|
1022
|
+
catch {
|
|
1023
|
+
console.warn('[agent-deck] Grant session refresh failed (transport kept):', `grantId=${principal.grantId}`);
|
|
1024
|
+
this.sendGrantRequired(res);
|
|
1025
|
+
return false;
|
|
1026
|
+
}
|
|
1027
|
+
// The unified authorization path: the session principal must allow
|
|
1028
|
+
// the requested deck. `principalAllowsDeck` is the same check local
|
|
1029
|
+
// launch sessions resolve through (local principals allow all).
|
|
1030
|
+
const header = readLaunchDeckHeader(req);
|
|
1031
|
+
const boundDeck = this.sessionBinding.getBinding(sessionId).deckId;
|
|
1032
|
+
if (header && header !== boundDeck && !(0, client_grants_1.principalAllowsDeck)(principal, header)) {
|
|
1033
|
+
this.getAuditStore()?.append({
|
|
1034
|
+
actor: principal.grantId,
|
|
1035
|
+
event: 'deck.selection_denied',
|
|
1036
|
+
targetId: (0, store_1.auditDeckTarget)(header),
|
|
1037
|
+
outcome: 'denied',
|
|
1038
|
+
reasonCode: 'resource_out_of_scope',
|
|
1039
|
+
});
|
|
1040
|
+
console.warn('[agent-deck] Grant follow-up deck denied (transport kept):', `grantId=${principal.grantId}`);
|
|
1041
|
+
this.sendOutOfScope(res);
|
|
1042
|
+
return false;
|
|
1043
|
+
}
|
|
1044
|
+
const workspaceRoot = readWorkspaceRootHeader(req);
|
|
1045
|
+
if (workspaceRoot) {
|
|
1046
|
+
this.sessionBinding.setWorkspace(sessionId, workspaceRoot);
|
|
1047
|
+
}
|
|
1048
|
+
const followUpCorrelation = readCorrelationIdHeader(req);
|
|
1049
|
+
if (followUpCorrelation) {
|
|
1050
|
+
this.sessionBinding.setCorrelationId(sessionId, followUpCorrelation);
|
|
1051
|
+
}
|
|
1052
|
+
return true;
|
|
1053
|
+
}
|
|
699
1054
|
async authenticateLaunchDeck(sessionId, req) {
|
|
700
1055
|
const deckId = readLaunchDeckHeader(req);
|
|
701
1056
|
if (!deckId) {
|
|
@@ -712,6 +1067,12 @@ class AgentDeckMCPServer {
|
|
|
712
1067
|
if (workspaceRoot) {
|
|
713
1068
|
this.sessionBinding.setWorkspace(sessionId, workspaceRoot);
|
|
714
1069
|
}
|
|
1070
|
+
// Adopt-once: a launch that arrived without correlation can still
|
|
1071
|
+
// attach one; an established value never moves (NOT-304).
|
|
1072
|
+
const followUpCorrelation = readCorrelationIdHeader(req);
|
|
1073
|
+
if (followUpCorrelation) {
|
|
1074
|
+
this.sessionBinding.setCorrelationId(sessionId, followUpCorrelation);
|
|
1075
|
+
}
|
|
715
1076
|
return;
|
|
716
1077
|
}
|
|
717
1078
|
const response = await fetch(`${this.backendUrl}/api/trusted-session/mcp/connect-deck`, {
|
|
@@ -735,9 +1096,16 @@ class AgentDeckMCPServer {
|
|
|
735
1096
|
workspaceRoot,
|
|
736
1097
|
mode: body.data.mode,
|
|
737
1098
|
});
|
|
1099
|
+
// Attach the opaque run-correlation id to this launch-selected session
|
|
1100
|
+
// (NOT-304). Adopt-once and validated inside the store: an invalid or
|
|
1101
|
+
// later-changed value can never affect deck, workspace, mode, or auth.
|
|
1102
|
+
const correlationId = readCorrelationIdHeader(req);
|
|
1103
|
+
if (correlationId) {
|
|
1104
|
+
this.sessionBinding.setCorrelationId(sessionId, correlationId);
|
|
1105
|
+
}
|
|
738
1106
|
}
|
|
739
1107
|
async disconnectTrustedSession(sessionId, _req) {
|
|
740
|
-
if (this.sessionBinding.isLaunchSession(sessionId)) {
|
|
1108
|
+
if (this.sessionBinding.isLaunchSession(sessionId) || this.sessionBinding.isGrantSession(sessionId)) {
|
|
741
1109
|
try {
|
|
742
1110
|
await fetch(`${this.backendUrl}/api/trusted-session/mcp/disconnect-deck`, {
|
|
743
1111
|
method: 'POST',
|
|
@@ -793,12 +1161,76 @@ class AgentDeckMCPServer {
|
|
|
793
1161
|
id: null,
|
|
794
1162
|
});
|
|
795
1163
|
}
|
|
1164
|
+
/**
|
|
1165
|
+
* NOT-318: initialize with a bearer grant. Authenticates before
|
|
1166
|
+
* advertising any `mcp-session-id`: failure answers the uniform 401
|
|
1167
|
+
* with no transport or session record created. Success binds the fresh
|
|
1168
|
+
* session to the grant-constrained deck (absent header → default;
|
|
1169
|
+
* out-of-grant header → 403, no session).
|
|
1170
|
+
*/
|
|
1171
|
+
async handleGrantInitialize(req, res, bearer) {
|
|
1172
|
+
const principal = this.authenticateGrant(bearer);
|
|
1173
|
+
if (!principal) {
|
|
1174
|
+
const presented = (0, client_grants_1.parseGrantToken)(bearer);
|
|
1175
|
+
console.warn('[agent-deck] Grant initialize auth failed (no session created):', `grantId=${presented?.grantId ?? 'none'}`);
|
|
1176
|
+
this.sendGrantRequired(res);
|
|
1177
|
+
return;
|
|
1178
|
+
}
|
|
1179
|
+
const deckId = (0, client_grants_1.resolveGrantDeck)(principal, readLaunchDeckHeader(req));
|
|
1180
|
+
if (!deckId) {
|
|
1181
|
+
this.getAuditStore()?.append({
|
|
1182
|
+
actor: principal.grantId,
|
|
1183
|
+
event: 'deck.selection_denied',
|
|
1184
|
+
targetId: (0, store_1.auditDeckTarget)(readLaunchDeckHeader(req)),
|
|
1185
|
+
outcome: 'denied',
|
|
1186
|
+
reasonCode: 'resource_out_of_scope',
|
|
1187
|
+
});
|
|
1188
|
+
console.warn('[agent-deck] Grant initialize deck denied (no session created):', `grantId=${principal.grantId}`);
|
|
1189
|
+
this.sendOutOfScope(res);
|
|
1190
|
+
return;
|
|
1191
|
+
}
|
|
1192
|
+
const sessionId = (0, node_crypto_1.randomUUID)();
|
|
1193
|
+
try {
|
|
1194
|
+
await this.authenticateGrantDeck(sessionId, req, principal, deckId);
|
|
1195
|
+
}
|
|
1196
|
+
catch (error) {
|
|
1197
|
+
console.warn('[agent-deck] Grant deck bind failed before MCP init (no session created):', `grantId=${principal.grantId}`, error instanceof Error ? error.message : error);
|
|
1198
|
+
this.sessionBinding.clearSession(sessionId);
|
|
1199
|
+
this.sendGrantRequired(res);
|
|
1200
|
+
return;
|
|
1201
|
+
}
|
|
1202
|
+
this.getAuditStore()?.append({
|
|
1203
|
+
actor: principal.grantId,
|
|
1204
|
+
event: 'grant.used',
|
|
1205
|
+
targetId: (0, store_1.auditDeckTarget)(deckId),
|
|
1206
|
+
outcome: 'succeeded',
|
|
1207
|
+
reasonCode: null,
|
|
1208
|
+
});
|
|
1209
|
+
await this.establishTransportSession(req, res, sessionId);
|
|
1210
|
+
}
|
|
796
1211
|
async handleMcpPost(req, res) {
|
|
797
1212
|
const sessionIdHeader = this.getSessionIdHeader(req);
|
|
798
1213
|
const existing = sessionIdHeader ? this.sessions.get(sessionIdHeader) : undefined;
|
|
1214
|
+
const bearerRequired = isBearerGrantRequired();
|
|
799
1215
|
if (existing && sessionIdHeader) {
|
|
800
|
-
|
|
801
|
-
|
|
1216
|
+
// Grant-bound sessions revalidate the bearer on every request and
|
|
1217
|
+
// never take the trust-the-header launch path: a forged deck header
|
|
1218
|
+
// is denied by the grant allowlist, not trusted into a new deck.
|
|
1219
|
+
if (this.sessionBinding.isGrantSession(sessionIdHeader)) {
|
|
1220
|
+
if (!(await this.requireGrantFollowUp(sessionIdHeader, req, res))) {
|
|
1221
|
+
return;
|
|
1222
|
+
}
|
|
1223
|
+
}
|
|
1224
|
+
else {
|
|
1225
|
+
// Hosted mode has no bearer-free sessions; a non-grant session id
|
|
1226
|
+
// is unusable there — fail closed before touching the transport.
|
|
1227
|
+
if (bearerRequired) {
|
|
1228
|
+
this.sendGrantRequired(res);
|
|
1229
|
+
return;
|
|
1230
|
+
}
|
|
1231
|
+
if (!(await this.requireFollowUpDeckHeader(sessionIdHeader, req, res))) {
|
|
1232
|
+
return;
|
|
1233
|
+
}
|
|
802
1234
|
}
|
|
803
1235
|
this.touchLiveDisplay(sessionIdHeader);
|
|
804
1236
|
await existing.transport.handleRequest(req, res, req.body);
|
|
@@ -809,7 +1241,30 @@ class AgentDeckMCPServer {
|
|
|
809
1241
|
typeof body === 'object' &&
|
|
810
1242
|
((0, types_js_1.isInitializeRequest)(body) ||
|
|
811
1243
|
(Array.isArray(body) && body.some((message) => (0, types_js_1.isInitializeRequest)(message))));
|
|
1244
|
+
if (isInit && process.env.AGENT_DECK_HOSTED_MODE === '1') {
|
|
1245
|
+
const principal = this.authenticateGrant(readBearerToken(req));
|
|
1246
|
+
const clientKey = principal
|
|
1247
|
+
? `grant:${principal.grantId}`
|
|
1248
|
+
: `ip:${req.socket.remoteAddress ?? 'unknown'}`;
|
|
1249
|
+
const rate = this.initializeLimiter.consume(clientKey, exports.MCP_INITIALIZE_RATE_LIMIT);
|
|
1250
|
+
if (!rate.allowed) {
|
|
1251
|
+
res.set('Retry-After', String(rate.retryAfterSeconds));
|
|
1252
|
+
res.status(429).json({
|
|
1253
|
+
jsonrpc: '2.0',
|
|
1254
|
+
error: { code: -32000, message: 'Too many initialize requests' },
|
|
1255
|
+
id: null,
|
|
1256
|
+
});
|
|
1257
|
+
return;
|
|
1258
|
+
}
|
|
1259
|
+
}
|
|
812
1260
|
if (!isInit) {
|
|
1261
|
+
// Hosted endpoints run the bearer-grant gate before session
|
|
1262
|
+
// existence: an unauthenticated prober gets 401, never the NOT-101
|
|
1263
|
+
// 404 body (which echoes the session id plus instance metadata).
|
|
1264
|
+
if (bearerRequired && !this.authenticateGrant(readBearerToken(req))) {
|
|
1265
|
+
this.sendGrantRequired(res);
|
|
1266
|
+
return;
|
|
1267
|
+
}
|
|
813
1268
|
// A session id we don't know is a restart, not a malformed request — 404 so
|
|
814
1269
|
// the client re-initializes. An initialize carrying a stale id falls through
|
|
815
1270
|
// and gets a fresh session, which is exactly the recovery we want.
|
|
@@ -824,6 +1279,18 @@ class AgentDeckMCPServer {
|
|
|
824
1279
|
});
|
|
825
1280
|
return;
|
|
826
1281
|
}
|
|
1282
|
+
// A presented bearer always resolves as a remote grant — even in local
|
|
1283
|
+
// mode — while loopback launcher connections without one keep the
|
|
1284
|
+
// existing deck-header path with zero config change.
|
|
1285
|
+
const presentedBearer = readBearerToken(req);
|
|
1286
|
+
if (presentedBearer) {
|
|
1287
|
+
await this.handleGrantInitialize(req, res, presentedBearer);
|
|
1288
|
+
return;
|
|
1289
|
+
}
|
|
1290
|
+
if (bearerRequired) {
|
|
1291
|
+
this.sendGrantRequired(res);
|
|
1292
|
+
return;
|
|
1293
|
+
}
|
|
827
1294
|
const launchDeck = readLaunchDeckHeader(req);
|
|
828
1295
|
const skipDeckHeader = (0, mcp_unassigned_1.skipDeckHeaderAuth)();
|
|
829
1296
|
const unassigned = !launchDeck && !skipDeckHeader;
|
|
@@ -834,6 +1301,13 @@ class AgentDeckMCPServer {
|
|
|
834
1301
|
await this.authenticateLaunchDeck(sessionId, req);
|
|
835
1302
|
}
|
|
836
1303
|
catch (error) {
|
|
1304
|
+
this.getAuditStore()?.append({
|
|
1305
|
+
actor: 'local-launch',
|
|
1306
|
+
event: 'deck.selection_denied',
|
|
1307
|
+
targetId: (0, store_1.auditDeckTarget)(launchDeck),
|
|
1308
|
+
outcome: 'denied',
|
|
1309
|
+
reasonCode: 'resource_out_of_scope',
|
|
1310
|
+
});
|
|
837
1311
|
console.warn('[agent-deck] Launch-deck auth failed before MCP init:', error instanceof Error ? error.message : error);
|
|
838
1312
|
this.sendLaunchDeckInvalid(res, error instanceof Error ? error.message : 'LAUNCH_DECK_INVALID');
|
|
839
1313
|
return;
|
|
@@ -846,7 +1320,17 @@ class AgentDeckMCPServer {
|
|
|
846
1320
|
this.sessionBinding.setWorkspace(sessionId, workspaceRoot);
|
|
847
1321
|
}
|
|
848
1322
|
}
|
|
849
|
-
|
|
1323
|
+
await this.establishTransportSession(req, res, sessionId);
|
|
1324
|
+
}
|
|
1325
|
+
/**
|
|
1326
|
+
* Shared transport handshake tail: create the per-session MCP server,
|
|
1327
|
+
* connect the streamable transport, and register the live session. Runs
|
|
1328
|
+
* only after the session is authenticated and bound (launch, grant, or
|
|
1329
|
+
* unassigned) — never before.
|
|
1330
|
+
*/
|
|
1331
|
+
async establishTransportSession(req, res, sessionId) {
|
|
1332
|
+
const body = req.body;
|
|
1333
|
+
const server = await this.createMcpServer(sessionId);
|
|
850
1334
|
let sessionEntry;
|
|
851
1335
|
const transport = new streamableHttp_js_1.StreamableHTTPServerTransport({
|
|
852
1336
|
sessionIdGenerator: () => sessionId,
|
|
@@ -877,7 +1361,7 @@ class AgentDeckMCPServer {
|
|
|
877
1361
|
await transport.handleRequest(req, res, body);
|
|
878
1362
|
}
|
|
879
1363
|
catch (error) {
|
|
880
|
-
console.warn('[agent-deck] MCP initialize failed after
|
|
1364
|
+
console.warn('[agent-deck] MCP initialize failed after session auth — revoking runtime session:', error instanceof Error ? error.message : error);
|
|
881
1365
|
this.sessions.delete(sessionId);
|
|
882
1366
|
await this.disconnectTrustedSession(sessionId, req);
|
|
883
1367
|
this.sessionBinding.clearSession(sessionId);
|
|
@@ -904,6 +1388,13 @@ class AgentDeckMCPServer {
|
|
|
904
1388
|
}
|
|
905
1389
|
async handleMcpSessionRequest(req, res) {
|
|
906
1390
|
const sessionId = this.getSessionIdHeader(req);
|
|
1391
|
+
const bearerRequired = isBearerGrantRequired();
|
|
1392
|
+
// Hosted endpoints run the Bearer [REDACTED] before session existence
|
|
1393
|
+
// (same no-oracle order as POST): 401 before any 404 metadata.
|
|
1394
|
+
if (bearerRequired && !this.authenticateGrant(readBearerToken(req))) {
|
|
1395
|
+
this.sendGrantRequired(res);
|
|
1396
|
+
return;
|
|
1397
|
+
}
|
|
907
1398
|
if (!sessionId) {
|
|
908
1399
|
res.status(400).send('Invalid or missing session ID');
|
|
909
1400
|
return;
|
|
@@ -913,8 +1404,19 @@ class AgentDeckMCPServer {
|
|
|
913
1404
|
this.sendSessionNotFound(sessionId, res);
|
|
914
1405
|
return;
|
|
915
1406
|
}
|
|
916
|
-
if (
|
|
917
|
-
|
|
1407
|
+
if (this.sessionBinding.isGrantSession(sessionId)) {
|
|
1408
|
+
if (!(await this.requireGrantFollowUp(sessionId, req, res))) {
|
|
1409
|
+
return;
|
|
1410
|
+
}
|
|
1411
|
+
}
|
|
1412
|
+
else {
|
|
1413
|
+
if (bearerRequired) {
|
|
1414
|
+
this.sendGrantRequired(res);
|
|
1415
|
+
return;
|
|
1416
|
+
}
|
|
1417
|
+
if (!(await this.requireFollowUpDeckHeader(sessionId, req, res))) {
|
|
1418
|
+
return;
|
|
1419
|
+
}
|
|
918
1420
|
}
|
|
919
1421
|
this.touchLiveDisplay(sessionId);
|
|
920
1422
|
await session.transport.handleRequest(req, res);
|
|
@@ -956,6 +1458,7 @@ class AgentDeckMCPServer {
|
|
|
956
1458
|
httpServer.once('error', reject);
|
|
957
1459
|
this.httpServer = httpServer;
|
|
958
1460
|
});
|
|
1461
|
+
this.startLiveDisplayKeepAlive();
|
|
959
1462
|
return this.app;
|
|
960
1463
|
}
|
|
961
1464
|
catch (error) {
|
|
@@ -966,6 +1469,7 @@ class AgentDeckMCPServer {
|
|
|
966
1469
|
}
|
|
967
1470
|
async stop() {
|
|
968
1471
|
try {
|
|
1472
|
+
this.stopLiveDisplayKeepAlive();
|
|
969
1473
|
for (const [sessionId, session] of this.sessions) {
|
|
970
1474
|
try {
|
|
971
1475
|
await session.transport.close();
|
|
@@ -981,6 +1485,10 @@ class AgentDeckMCPServer {
|
|
|
981
1485
|
// Release the port too, otherwise a restart on the same port races the old
|
|
982
1486
|
// listener and the "did it come back?" probe can't tell the two apart.
|
|
983
1487
|
await this.closeHttpServer();
|
|
1488
|
+
this.sharedSecurityDb?.close();
|
|
1489
|
+
this.sharedSecurityDb = null;
|
|
1490
|
+
this.grantStoreCache = null;
|
|
1491
|
+
this.auditStoreCache = null;
|
|
984
1492
|
console.log(`🛑 MCP server stopped`);
|
|
985
1493
|
}
|
|
986
1494
|
catch (error) {
|