@tempad-dev/mcp 0.6.3 → 0.7.1

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/hub.mjs CHANGED
@@ -1,15 +1,15 @@
1
- import { c as SOCK_PATH, d as log, i as HUB_LOCK_UPDATE_MS, l as ensureDir, n as HUB_LOCK_PATH, o as PACKAGE_VERSION, r as HUB_LOCK_STALE_MS, s as RUNTIME_DIR, t as ASSET_DIR, u as ensureFile } from "./shared-CaWmhDVA.mjs";
1
+ import { c as SOCK_PATH, d as log, i as HUB_LOCK_UPDATE_MS, l as ensureDir, n as HUB_LOCK_PATH, o as PACKAGE_VERSION, r as HUB_LOCK_STALE_MS, s as RUNTIME_DIR, t as ASSET_DIR, u as ensureFile } from "./shared-Df79xZoB.mjs";
2
2
  import { connect, createServer } from "node:net";
3
3
  import { join } from "node:path";
4
- import { URL } from "node:url";
4
+ import { URL as URL$1 } from "node:url";
5
5
  import lockfile from "proper-lockfile";
6
6
  import { chmodSync, createReadStream, createWriteStream, existsSync, readFileSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
7
7
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
8
8
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
9
9
  import { z } from "zod";
10
- import { nanoid } from "nanoid";
10
+ import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
11
11
  import { WebSocketServer } from "ws";
12
- import { createHash } from "node:crypto";
12
+ import { nanoid } from "nanoid";
13
13
  import { createServer as createServer$1 } from "node:http";
14
14
  import { Transform, pipeline } from "node:stream";
15
15
  //#region ../shared/dist/index.js
@@ -23,6 +23,7 @@ const MCP_TOOL_INLINE_BUDGET_BYTES = 64 * 1024;
23
23
  const MCP_TOOL_TIMEOUT_MS = 15e3;
24
24
  const MCP_AUTO_ACTIVATE_GRACE_MS = 1500;
25
25
  const MCP_MAX_ASSET_BYTES = 8 * 1024 * 1024;
26
+ const MCP_MAX_ASSET_STORE_BYTES = 256 * 1024 * 1024;
26
27
  const MCP_ASSET_TTL_MS = 720 * 60 * 60 * 1e3;
27
28
  const MCP_HASH_PATTERN = new RegExp(`^[a-f0-9]{8}$`, "i");
28
29
  const TEMPAD_MCP_ERROR_CODES = {
@@ -34,8 +35,18 @@ const TEMPAD_MCP_ERROR_CODES = {
34
35
  ASSET_SERVER_NOT_CONFIGURED: "ASSET_SERVER_NOT_CONFIGURED",
35
36
  TRANSPORT_NOT_CONNECTED: "TRANSPORT_NOT_CONNECTED"
36
37
  };
38
+ const TempadMcpErrorPayloadSchema = z.object({
39
+ code: z.enum(TEMPAD_MCP_ERROR_CODES).optional(),
40
+ message: z.string().min(1)
41
+ }).strict();
42
+ const TOOL_RESULT_OUTCOME_ERROR = "Tool results must contain exactly one defined payload or error.";
43
+ function hasToolResultOutcome(result) {
44
+ return result.payload !== void 0 !== (result.error !== void 0);
45
+ }
46
+ const TEMPAD_MCP_BROWSER_SOURCE = "tempad-dev:mcp";
47
+ const MCP_MAX_ASSET_BASE64_LENGTH = 4 * Math.ceil(MCP_MAX_ASSET_BYTES / 3);
37
48
  const MessageBaseSchema = z.object({
38
- source: z.literal("tempad-dev:mcp"),
49
+ source: z.literal(TEMPAD_MCP_BROWSER_SOURCE),
39
50
  version: z.literal(1)
40
51
  }).strict();
41
52
  const PageMessageBaseSchema = MessageBaseSchema.extend({ sessionId: z.string().min(1) }).strict();
@@ -45,17 +56,13 @@ function messageSchema(base, type, shape) {
45
56
  ...shape
46
57
  }).strict();
47
58
  }
48
- const ToolErrorSchema = z.object({
49
- code: z.enum(TEMPAD_MCP_ERROR_CODES).optional(),
50
- message: z.string()
51
- }).strict();
52
59
  const AssetMetadataSchema = z.object({
53
60
  height: z.number().int().positive().optional(),
54
61
  themeable: z.boolean().optional(),
55
62
  width: z.number().int().positive().optional()
56
63
  }).strict();
57
64
  const AssetUploadPayloadSchema = z.object({
58
- base64: z.string().min(1),
65
+ base64: z.string().min(1).max(MCP_MAX_ASSET_BASE64_LENGTH),
59
66
  hash: z.string().regex(MCP_HASH_PATTERN),
60
67
  metadata: AssetMetadataSchema.optional(),
61
68
  mimeType: z.string().min(1)
@@ -65,7 +72,7 @@ const PageDisableMessageSchema = messageSchema(PageMessageBaseSchema, "mcp.disab
65
72
  const PageActivateSessionMessageSchema = messageSchema(PageMessageBaseSchema, "mcp.activateSession", {});
66
73
  const PageToolResultMessageSchema = messageSchema(PageMessageBaseSchema, "mcp.toolResult", {
67
74
  callId: z.string().min(1),
68
- error: ToolErrorSchema.optional(),
75
+ error: TempadMcpErrorPayloadSchema.optional(),
69
76
  payload: z.unknown().optional()
70
77
  });
71
78
  const PageAssetUploadMessageSchema = messageSchema(PageMessageBaseSchema, "mcp.uploadAsset", {
@@ -78,7 +85,9 @@ z.discriminatedUnion("type", [
78
85
  PageActivateSessionMessageSchema,
79
86
  PageToolResultMessageSchema,
80
87
  PageAssetUploadMessageSchema
81
- ]);
88
+ ]).refine((message) => {
89
+ return message.type !== "mcp.toolResult" || hasToolResultOutcome(message);
90
+ }, { message: TOOL_RESULT_OUTCOME_ERROR });
82
91
  const McpBrowserStateStatusSchema = z.enum([
83
92
  "disabled",
84
93
  "connecting",
@@ -101,7 +110,7 @@ const BridgeToolCallMessageSchema = messageSchema(MessageBaseSchema, "mcp.toolCa
101
110
  }).strict()
102
111
  });
103
112
  const BridgeAssetUploadResultMessageSchema = messageSchema(MessageBaseSchema, "mcp.assetUploadResult", {
104
- error: ToolErrorSchema.optional(),
113
+ error: TempadMcpErrorPayloadSchema.optional(),
105
114
  requestId: z.string().min(1),
106
115
  sessionId: z.string().min(1)
107
116
  });
@@ -113,6 +122,11 @@ z.discriminatedUnion("type", [
113
122
  const SERVER_NAME = "tempad-dev";
114
123
  const SERVER_COMMAND = "npx";
115
124
  const SERVER_ARGS = ["-y", "@tempad-dev/mcp@latest"];
125
+ const REPOSITORY = "ecomfe/tempad-dev";
126
+ const MARKETPLACE_NAME = "tempad-dev";
127
+ const PLUGIN_NAME = "tempad-dev";
128
+ const SKILL_URL = "https://github.com/ecomfe/tempad-dev/tree/main/skill";
129
+ const SKILL_INSTALL_COMMAND = `npx skills add ${SKILL_URL}`;
116
130
  const stdioConfig = {
117
131
  type: "stdio",
118
132
  command: SERVER_COMMAND,
@@ -150,13 +164,40 @@ function buildCodexConfigSnippet() {
150
164
  `args = [${SERVER_ARGS.map((arg) => JSON.stringify(arg)).join(", ")}]`
151
165
  ].join("\n");
152
166
  }
167
+ function buildMcpConfigSnippet() {
168
+ return JSON.stringify({ mcpServers: { [SERVER_NAME]: commandConfig } }, null, 2);
169
+ }
170
+ const OPENCODE_CONFIG_SNIPPET = JSON.stringify({
171
+ $schema: "https://opencode.ai/config.json",
172
+ mcp: { [SERVER_NAME]: {
173
+ type: "local",
174
+ command: [SERVER_COMMAND, ...SERVER_ARGS]
175
+ } }
176
+ }, null, 2);
153
177
  function buildCliCommand(prefix) {
154
178
  const args = `${SERVER_COMMAND} ${SERVER_ARGS.join(" ")}`;
155
179
  if (prefix === "claude") return `claude mcp add --transport stdio "${SERVER_NAME}" -- ${args}`;
180
+ if (prefix === "gemini") return `gemini mcp add --scope user "${SERVER_NAME}" ${args}`;
181
+ if (prefix === "vscode") return `code --add-mcp '${JSON.stringify({
182
+ name: SERVER_NAME,
183
+ ...commandConfig
184
+ })}'`;
156
185
  return `codex mcp add "${SERVER_NAME}" -- ${args}`;
157
186
  }
187
+ function buildPluginSetupCommand(prefix) {
188
+ if (prefix === "claude") return [`claude plugin marketplace add ${REPOSITORY}`, `claude plugin install ${PLUGIN_NAME}@${MARKETPLACE_NAME}`].join(" && ");
189
+ return [`codex plugin marketplace add ${REPOSITORY} --ref main`, `codex plugin add ${PLUGIN_NAME}@${MARKETPLACE_NAME}`].join(" && ");
190
+ }
191
+ function buildPluginSetupDeepLink(prefix) {
192
+ const prompt = `Install the TemPad Dev agent plugin by running this command, then confirm that its MCP server and figma-design-to-code skill are available:\n\n${buildPluginSetupCommand(prefix)}`;
193
+ return `${prefix === "claude" ? "claude-cli://open?q=" : "codex://new?prompt="}${encodeURIComponent(prompt)}`;
194
+ }
195
+ function buildSkillInstallCommand(...agents) {
196
+ return `${SKILL_INSTALL_COMMAND} --global ${agents.map((agent) => `--agent ${agent}`).join(" ")}`;
197
+ }
158
198
  [...SERVER_ARGS];
159
199
  JSON.stringify({ [SERVER_NAME]: commandConfig }, null, 2);
200
+ buildMcpConfigSnippet();
160
201
  const MCP_CLIENTS_BY_ID = {
161
202
  vscode: {
162
203
  id: "vscode",
@@ -182,7 +223,7 @@ const MCP_CLIENTS_BY_ID = {
182
223
  },
183
224
  codex: {
184
225
  id: "codex",
185
- name: "Codex CLI",
226
+ name: "Codex",
186
227
  brandColor: ["#0d0d0d", "#fff"],
187
228
  supportsDeepLink: false,
188
229
  copyText: buildCliCommand("codex"),
@@ -190,6 +231,24 @@ const MCP_CLIENTS_BY_ID = {
190
231
  alternateCopyText: buildCodexConfigSnippet(),
191
232
  alternateCopyKind: "config"
192
233
  },
234
+ gemini: {
235
+ id: "gemini",
236
+ name: "Gemini",
237
+ brandColor: "#4e6ef2",
238
+ supportsDeepLink: false,
239
+ copyText: buildCliCommand("gemini"),
240
+ copyKind: "command",
241
+ alternateCopyText: buildMcpConfigSnippet(),
242
+ alternateCopyKind: "config"
243
+ },
244
+ opencode: {
245
+ id: "opencode",
246
+ name: "OpenCode",
247
+ brandColor: ["#211e1e", "#f1ecec"],
248
+ supportsDeepLink: false,
249
+ copyText: OPENCODE_CONFIG_SNIPPET,
250
+ copyKind: "config"
251
+ },
193
252
  trae: {
194
253
  id: "trae",
195
254
  name: "TRAE",
@@ -199,10 +258,137 @@ const MCP_CLIENTS_BY_ID = {
199
258
  fallbackDeepLink: buildTraeDeepLink("trae-cn")
200
259
  }
201
260
  };
202
- MCP_CLIENTS_BY_ID.vscode, MCP_CLIENTS_BY_ID.cursor, MCP_CLIENTS_BY_ID.claude, MCP_CLIENTS_BY_ID.codex, MCP_CLIENTS_BY_ID.trae;
261
+ MCP_CLIENTS_BY_ID.vscode, MCP_CLIENTS_BY_ID.cursor, MCP_CLIENTS_BY_ID.claude, MCP_CLIENTS_BY_ID.codex, MCP_CLIENTS_BY_ID.gemini, MCP_CLIENTS_BY_ID.opencode, MCP_CLIENTS_BY_ID.trae;
262
+ const AGENT_INTEGRATIONS_BY_ID = {
263
+ codex: {
264
+ id: "codex",
265
+ name: "Codex",
266
+ actions: [{
267
+ id: "plugin-prompt",
268
+ label: "Plugin install",
269
+ kind: "deep-link",
270
+ value: buildPluginSetupDeepLink("codex")
271
+ }, {
272
+ id: "plugin-cli",
273
+ label: "Plugin CLI",
274
+ kind: "command",
275
+ value: buildPluginSetupCommand("codex")
276
+ }]
277
+ },
278
+ cursor: {
279
+ id: "cursor",
280
+ name: "Cursor",
281
+ actions: [
282
+ {
283
+ id: "mcp-deep-link",
284
+ label: "MCP install",
285
+ kind: "deep-link",
286
+ value: MCP_CLIENTS_BY_ID.cursor.deepLink ?? ""
287
+ },
288
+ {
289
+ id: "mcp-config",
290
+ label: "MCP config",
291
+ kind: "config",
292
+ value: buildMcpConfigSnippet()
293
+ },
294
+ {
295
+ id: "skill-cli",
296
+ label: "Agent skill",
297
+ kind: "command",
298
+ value: buildSkillInstallCommand("cursor")
299
+ }
300
+ ]
301
+ },
302
+ claude: {
303
+ id: "claude",
304
+ name: "Claude Code",
305
+ actions: [{
306
+ id: "plugin-prompt",
307
+ label: "Plugin install",
308
+ kind: "deep-link",
309
+ value: buildPluginSetupDeepLink("claude")
310
+ }, {
311
+ id: "plugin-cli",
312
+ label: "Plugin CLI",
313
+ kind: "command",
314
+ value: buildPluginSetupCommand("claude")
315
+ }]
316
+ },
317
+ gemini: {
318
+ id: "gemini",
319
+ name: "Gemini",
320
+ actions: [{
321
+ id: "mcp-cli",
322
+ label: "MCP CLI",
323
+ kind: "command",
324
+ value: buildCliCommand("gemini")
325
+ }, {
326
+ id: "skill-cli",
327
+ label: "Agent skill",
328
+ kind: "command",
329
+ value: `gemini skills install ${SKILL_URL}`
330
+ }]
331
+ },
332
+ vscode: {
333
+ id: "vscode",
334
+ name: "VS Code",
335
+ actions: [
336
+ {
337
+ id: "mcp-deep-link",
338
+ label: "MCP install",
339
+ kind: "deep-link",
340
+ value: MCP_CLIENTS_BY_ID.vscode.deepLink ?? ""
341
+ },
342
+ {
343
+ id: "mcp-cli",
344
+ label: "MCP CLI",
345
+ kind: "command",
346
+ value: buildCliCommand("vscode")
347
+ },
348
+ {
349
+ id: "skill-cli",
350
+ label: "Agent skill",
351
+ kind: "command",
352
+ value: buildSkillInstallCommand("github-copilot")
353
+ }
354
+ ]
355
+ },
356
+ opencode: {
357
+ id: "opencode",
358
+ name: "OpenCode",
359
+ actions: [{
360
+ id: "mcp-config",
361
+ label: "MCP config",
362
+ kind: "config",
363
+ value: OPENCODE_CONFIG_SNIPPET
364
+ }, {
365
+ id: "skill-cli",
366
+ label: "Agent skill",
367
+ kind: "command",
368
+ value: buildSkillInstallCommand("opencode")
369
+ }]
370
+ },
371
+ trae: {
372
+ id: "trae",
373
+ name: "TRAE",
374
+ actions: [{
375
+ id: "mcp-deep-link",
376
+ label: "MCP install",
377
+ kind: "deep-link",
378
+ value: MCP_CLIENTS_BY_ID.trae.deepLink ?? "",
379
+ fallbackValue: MCP_CLIENTS_BY_ID.trae.fallbackDeepLink
380
+ }, {
381
+ id: "skill-cli",
382
+ label: "Agent skill",
383
+ kind: "command",
384
+ value: buildSkillInstallCommand("trae", "trae-cn")
385
+ }]
386
+ }
387
+ };
388
+ AGENT_INTEGRATIONS_BY_ID.codex, AGENT_INTEGRATIONS_BY_ID.cursor, AGENT_INTEGRATIONS_BY_ID.claude, AGENT_INTEGRATIONS_BY_ID.gemini, AGENT_INTEGRATIONS_BY_ID.vscode, AGENT_INTEGRATIONS_BY_ID.opencode, AGENT_INTEGRATIONS_BY_ID.trae;
203
389
  const RegisteredMessageSchema = z.object({
204
390
  type: z.literal("registered"),
205
- id: z.string()
391
+ id: z.string().min(1)
206
392
  }).strict();
207
393
  const StateMessageSchema = z.object({
208
394
  type: z.literal("state"),
@@ -215,7 +401,7 @@ const ToolCallPayloadSchema = z.object({
215
401
  }).strict();
216
402
  const ToolCallMessageSchema = z.object({
217
403
  type: z.literal("toolCall"),
218
- id: z.string(),
404
+ id: z.string().min(1),
219
405
  payload: ToolCallPayloadSchema
220
406
  }).strict();
221
407
  z.discriminatedUnion("type", [
@@ -226,12 +412,12 @@ z.discriminatedUnion("type", [
226
412
  const ActivateMessageSchema = z.object({ type: z.literal("activate") }).strict();
227
413
  const ToolResultMessageSchema = z.object({
228
414
  type: z.literal("toolResult"),
229
- id: z.string(),
415
+ id: z.string().min(1),
230
416
  payload: z.unknown().optional(),
231
- error: z.unknown().optional()
232
- }).strict();
417
+ error: TempadMcpErrorPayloadSchema.optional()
418
+ }).strict().refine(hasToolResultOutcome, { message: TOOL_RESULT_OUTCOME_ERROR });
233
419
  const PingMessageSchema = z.object({ type: z.literal("ping") }).strict();
234
- const MessageFromExtensionSchema = z.discriminatedUnion("type", [
420
+ const MessageFromExtensionSchema = z.union([
235
421
  ActivateMessageSchema,
236
422
  ToolResultMessageSchema,
237
423
  PingMessageSchema
@@ -309,7 +495,7 @@ function describeScreenshot(result) {
309
495
  return `Screenshot ${result.width}x${result.height} @${result.scale}x (${formatBytes(result.bytes)})`;
310
496
  }
311
497
  const AssetDescriptorSchema = z.object({
312
- hash: z.string().min(1),
498
+ hash: z.string().regex(MCP_HASH_PATTERN),
313
499
  url: z.string().url(),
314
500
  mimeType: z.string().min(1),
315
501
  size: z.number().int().nonnegative(),
@@ -335,7 +521,7 @@ const GetStructureParametersSchema = z.object({
335
521
  const GetAssetsParametersSchema = z.object({ hashes: z.array(z.string().regex(MCP_HASH_PATTERN)).min(1).describe("Asset hashes returned from get_code (or other tools) to download/resolve exact bytes for rasterized images or SVGs before routing through your asset pipeline.") });
336
522
  const GetAssetsResultSchema = z.object({
337
523
  assets: z.array(AssetDescriptorSchema),
338
- missing: z.array(z.string().min(1))
524
+ missing: z.array(z.string().regex(MCP_HASH_PATTERN))
339
525
  });
340
526
  //#endregion
341
527
  //#region src/asset-utils.ts
@@ -388,6 +574,15 @@ function resolveMaxAssetSizeBytes() {
388
574
  function resolveAssetTtlMs() {
389
575
  return parseNonNegativeInt(process.env.TEMPAD_MCP_ASSET_TTL_MS, MCP_ASSET_TTL_MS);
390
576
  }
577
+ function resolveMaxAssetStoreBytes() {
578
+ return parsePositiveInt(process.env.TEMPAD_MCP_MAX_ASSET_STORE_BYTES, MCP_MAX_ASSET_STORE_BYTES);
579
+ }
580
+ function resolveMaxConcurrentAssetUploads() {
581
+ return parsePositiveInt(process.env.TEMPAD_MCP_MAX_CONCURRENT_ASSET_UPLOADS, 4);
582
+ }
583
+ function resolveMaxExtensionConnections() {
584
+ return parsePositiveInt(process.env.TEMPAD_MCP_MAX_EXTENSION_CONNECTIONS, 16);
585
+ }
391
586
  function getMcpServerConfig() {
392
587
  return {
393
588
  wsPortCandidates: [...MCP_PORT_CANDIDATES],
@@ -395,17 +590,81 @@ function getMcpServerConfig() {
395
590
  maxPayloadBytes: MCP_MAX_PAYLOAD_BYTES,
396
591
  autoActivateGraceMs: resolveAutoActivateGraceMs(),
397
592
  maxAssetSizeBytes: resolveMaxAssetSizeBytes(),
593
+ maxAssetStoreBytes: resolveMaxAssetStoreBytes(),
594
+ maxConcurrentAssetUploads: resolveMaxConcurrentAssetUploads(),
595
+ maxExtensionConnections: resolveMaxExtensionConnections(),
596
+ allowedExtensionOrigins: process.env.TEMPAD_MCP_ALLOWED_EXTENSION_ORIGINS,
398
597
  assetTtlMs: resolveAssetTtlMs()
399
598
  };
400
599
  }
401
600
  //#endregion
601
+ //#region src/security.ts
602
+ const CHROME_EXTENSION_ORIGIN_PATTERN = /^chrome-extension:\/\/[a-p]{32}$/;
603
+ function createCapabilityToken() {
604
+ return randomBytes(32).toString("base64url");
605
+ }
606
+ function createExtensionOriginPolicy(value) {
607
+ const configuredOrigins = (value ?? "").split(",").map((origin) => origin.trim().toLowerCase()).filter(Boolean);
608
+ const invalidOrigin = configuredOrigins.find((origin) => !isChromeExtensionOrigin(origin));
609
+ if (invalidOrigin) throw new Error(`Invalid allowed extension Origin: ${invalidOrigin}`);
610
+ const exactOrigins = new Set(configuredOrigins);
611
+ return {
612
+ exactOrigins,
613
+ mode: exactOrigins.size ? "exact" : "any-extension"
614
+ };
615
+ }
616
+ function isAllowedExtensionOrigin(origin, policy) {
617
+ if (!origin) return false;
618
+ const normalized = origin.toLowerCase();
619
+ if (!isChromeExtensionOrigin(normalized)) return false;
620
+ return policy.mode === "any-extension" || policy.exactOrigins.has(normalized);
621
+ }
622
+ function isAllowedWebSocketRequest(origin, requestUrl, policy) {
623
+ if (!isAllowedExtensionOrigin(origin, policy)) return false;
624
+ if (!requestUrl) return false;
625
+ try {
626
+ const baseUrl = "ws://127.0.0.1";
627
+ const url = new URL(requestUrl, baseUrl);
628
+ return url.origin === baseUrl && url.pathname === "/" && url.search === "";
629
+ } catch {
630
+ return false;
631
+ }
632
+ }
633
+ function secretsEqual(candidate, expected) {
634
+ const candidateBuffer = Buffer.from(candidate);
635
+ const expectedBuffer = Buffer.from(expected);
636
+ return candidateBuffer.length === expectedBuffer.length && timingSafeEqual(candidateBuffer, expectedBuffer);
637
+ }
638
+ function isChromeExtensionOrigin(origin) {
639
+ return CHROME_EXTENSION_ORIGIN_PATTERN.test(origin);
640
+ }
641
+ //#endregion
402
642
  //#region src/asset-http-server.ts
403
643
  const LOOPBACK_HOST = "127.0.0.1";
404
644
  const HASH_HEX_PATTERN = new RegExp(`^[a-f0-9]{8}$`, "i");
405
- const { maxAssetSizeBytes } = getMcpServerConfig();
406
- function createAssetHttpServer(store) {
645
+ const ASSET_REQUEST_TIMEOUT_MS = 15e3;
646
+ const ASSET_HEADERS_TIMEOUT_MS = 5e3;
647
+ const ASSET_KEEP_ALIVE_TIMEOUT_MS = 5e3;
648
+ const ASSET_MAX_HEADERS = 32;
649
+ const ASSET_MAX_CONNECTIONS = 128;
650
+ const ASSET_MAX_CONCURRENT_DOWNLOADS = 128;
651
+ function createAssetHttpServer(store, options = {}) {
652
+ const config = getMcpServerConfig();
653
+ const accessToken = options.accessToken ?? createCapabilityToken();
654
+ const maxAssetSizeBytes = options.maxAssetSizeBytes ?? config.maxAssetSizeBytes;
655
+ const maxAssetStoreBytes = options.maxAssetStoreBytes ?? config.maxAssetStoreBytes;
656
+ const maxConcurrentUploads = options.maxConcurrentUploads ?? config.maxConcurrentAssetUploads;
657
+ const originPolicy = createExtensionOriginPolicy(config.allowedExtensionOrigins);
407
658
  const server = createServer$1(handleRequest);
659
+ server.requestTimeout = ASSET_REQUEST_TIMEOUT_MS;
660
+ server.headersTimeout = ASSET_HEADERS_TIMEOUT_MS;
661
+ server.keepAliveTimeout = ASSET_KEEP_ALIVE_TIMEOUT_MS;
662
+ server.maxHeadersCount = ASSET_MAX_HEADERS;
663
+ server.maxConnections = ASSET_MAX_CONNECTIONS;
408
664
  let port = null;
665
+ let activeDownloads = 0;
666
+ let activeUploads = 0;
667
+ let reservedUploadBytes = 0;
409
668
  async function start() {
410
669
  if (port !== null) return;
411
670
  await new Promise((resolve, reject) => {
@@ -434,36 +693,44 @@ function createAssetHttpServer(store) {
434
693
  }
435
694
  function getBaseUrl() {
436
695
  if (port === null) throw new Error("Asset HTTP server is not running.");
437
- return `http://${LOOPBACK_HOST}:${port}`;
696
+ return `http://${LOOPBACK_HOST}:${port}/${accessToken}`;
438
697
  }
439
698
  function handleRequest(req, res) {
440
699
  const startedAt = Date.now();
441
700
  res.on("finish", () => {
442
701
  log.info({
443
702
  method: req.method,
444
- url: req.url,
703
+ route: redactAssetRequestUrl(req.url),
445
704
  status: res.statusCode,
446
705
  durationMs: Date.now() - startedAt
447
706
  }, "HTTP asset request completed.");
448
707
  });
449
- res.setHeader("Access-Control-Allow-Origin", "*");
450
- res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
451
- res.setHeader("Access-Control-Allow-Headers", "Content-Type, X-Asset-Width, X-Asset-Height, X-Asset-Themeable");
452
- if (req.method === "OPTIONS") {
453
- res.writeHead(204);
454
- res.end();
455
- return;
456
- }
457
708
  if (!req.url) {
458
709
  sendError(res, 400, "Missing URL");
459
710
  return;
460
711
  }
461
- const segments = new URL(req.url, getBaseUrl()).pathname.split("/").filter(Boolean);
462
- if (segments.length !== 2 || segments[0] !== "assets") {
712
+ const segments = new URL$1(req.url, getBaseUrl()).pathname.split("/").filter(Boolean);
713
+ if (segments.length !== 3 || !secretsEqual(segments[0] ?? "", accessToken) || segments[1] !== "assets") {
463
714
  sendError(res, 404, "Not Found");
464
715
  return;
465
716
  }
466
- const filename = segments[1];
717
+ const origin = getHeader(req, "origin");
718
+ if (origin && (!isAllowedExtensionOrigin(origin, originPolicy) || options.authorizeExtensionOrigin && !options.authorizeExtensionOrigin(origin))) {
719
+ sendError(res, 403, "Forbidden");
720
+ return;
721
+ }
722
+ if (origin) {
723
+ res.setHeader("Access-Control-Allow-Origin", origin);
724
+ res.setHeader("Vary", "Origin");
725
+ res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
726
+ res.setHeader("Access-Control-Allow-Headers", "Content-Type, X-Asset-Width, X-Asset-Height, X-Asset-Themeable");
727
+ }
728
+ if (req.method === "OPTIONS") {
729
+ res.writeHead(204);
730
+ res.end();
731
+ return;
732
+ }
733
+ const filename = segments[2];
467
734
  const hash = getHashFromAssetFilename(filename);
468
735
  if (!hash) {
469
736
  sendError(res, 404, "Not Found");
@@ -501,10 +768,29 @@ function createAssetHttpServer(store) {
501
768
  }
502
769
  return;
503
770
  }
771
+ if (activeDownloads >= ASSET_MAX_CONCURRENT_DOWNLOADS) {
772
+ res.setHeader("Connection", "close");
773
+ sendError(res, 429, "Too Many Concurrent Downloads");
774
+ return;
775
+ }
776
+ activeDownloads += 1;
777
+ let released = false;
778
+ const release = () => {
779
+ if (released) return;
780
+ released = true;
781
+ activeDownloads -= 1;
782
+ };
783
+ res.once("finish", release);
784
+ res.once("close", release);
785
+ res.setTimeout(ASSET_REQUEST_TIMEOUT_MS, () => res.destroy());
504
786
  res.writeHead(200, {
505
787
  "Content-Type": record.mimeType,
506
788
  "Content-Length": stat.size.toString(),
507
- "Cache-Control": "public, max-age=31536000, immutable"
789
+ "Cache-Control": "private, max-age=31536000, immutable",
790
+ "Content-Disposition": `attachment; filename="${buildAssetFilename(hash, record.mimeType)}"`,
791
+ "Content-Security-Policy": "default-src 'none'; sandbox",
792
+ "Referrer-Policy": "no-referrer",
793
+ "X-Content-Type-Options": "nosniff"
508
794
  });
509
795
  const stream = createReadStream(record.filePath);
510
796
  stream.on("error", (error) => {
@@ -526,13 +812,22 @@ function createAssetHttpServer(store) {
526
812
  sendError(res, 400, "Invalid Hash");
527
813
  return;
528
814
  }
529
- const contentTypeHeader = req.headers["content-type"];
530
- const mimeType = normalizeMimeType(Array.isArray(contentTypeHeader) ? contentTypeHeader[0] : contentTypeHeader);
815
+ const declaredSize = parseContentLength(req);
816
+ if (declaredSize === "invalid") {
817
+ req.resume();
818
+ sendError(res, 400, "Invalid Content-Length");
819
+ return;
820
+ }
821
+ if (declaredSize !== null && declaredSize > maxAssetSizeBytes) {
822
+ req.resume();
823
+ sendError(res, 413, "Payload Too Large");
824
+ return;
825
+ }
826
+ const mimeType = normalizeMimeType(getHeader(req, "content-type"));
531
827
  const filePath = join(ASSET_DIR, buildAssetFilename(hash, mimeType));
532
- const width = parseInt(req.headers["x-asset-width"], 10);
533
- const height = parseInt(req.headers["x-asset-height"], 10);
534
- const themeableHeader = req.headers["x-asset-themeable"];
535
- const themeable = (Array.isArray(themeableHeader) ? themeableHeader[0] : themeableHeader) === "true";
828
+ const width = parseInt(getHeader(req, "x-asset-width") ?? "", 10);
829
+ const height = parseInt(getHeader(req, "x-asset-height") ?? "", 10);
830
+ const themeable = getHeader(req, "x-asset-themeable") === "true";
536
831
  const metadata = {};
537
832
  if (Number.isFinite(width) && width > 0) metadata.width = width;
538
833
  if (Number.isFinite(height) && height > 0) metadata.height = height;
@@ -563,14 +858,28 @@ function createAssetHttpServer(store) {
563
858
  if (existing.mimeType !== mimeType) existing.mimeType = mimeType;
564
859
  existing.lastAccess = Date.now();
565
860
  store.upsert(existing);
566
- sendOk(res, 200, "Asset Already Exists");
861
+ sendJson(res, 200, { message: "Asset Already Exists" });
567
862
  return;
568
863
  }
569
864
  }
865
+ if (activeUploads >= maxConcurrentUploads) {
866
+ req.resume();
867
+ res.setHeader("Connection", "close");
868
+ sendError(res, 429, "Too Many Concurrent Uploads");
869
+ return;
870
+ }
871
+ const reservationBytes = declaredSize ?? maxAssetSizeBytes;
872
+ if (getStoredAssetBytes(store, hash) + reservedUploadBytes + reservationBytes > maxAssetStoreBytes) {
873
+ req.resume();
874
+ sendError(res, 507, "Asset Store Quota Exceeded");
875
+ return;
876
+ }
570
877
  const tmpPath = `${filePath}.tmp.${nanoid()}`;
571
878
  const writeStream = createWriteStream(tmpPath);
572
879
  const hasher = createHash("sha256");
573
880
  let size = 0;
881
+ activeUploads += 1;
882
+ reservedUploadBytes += reservationBytes;
574
883
  const cleanup = () => {
575
884
  if (existsSync(tmpPath)) try {
576
885
  unlinkSync(tmpPath);
@@ -590,6 +899,8 @@ function createAssetHttpServer(store) {
590
899
  hasher.update(chunk);
591
900
  callback(null, chunk);
592
901
  } }), writeStream, (err) => {
902
+ activeUploads -= 1;
903
+ reservedUploadBytes -= reservationBytes;
593
904
  if (err) {
594
905
  cleanup();
595
906
  if (err.message === "PayloadTooLarge") sendError(res, 413, "Payload Too Large");
@@ -610,6 +921,11 @@ function createAssetHttpServer(store) {
610
921
  sendError(res, 400, "Hash Mismatch");
611
922
  return;
612
923
  }
924
+ if (getStoredAssetBytes(store, hash) + reservedUploadBytes + size > maxAssetStoreBytes) {
925
+ cleanup();
926
+ sendError(res, 507, "Asset Store Quota Exceeded");
927
+ return;
928
+ }
613
929
  try {
614
930
  renameSync(tmpPath, filePath);
615
931
  } catch (error) {
@@ -632,25 +948,32 @@ function createAssetHttpServer(store) {
632
948
  hash,
633
949
  size
634
950
  }, "Stored uploaded asset via HTTP.");
635
- sendOk(res, 201, "Created", {
951
+ sendJson(res, 201, {
952
+ message: "Created",
636
953
  hash,
637
954
  size
638
955
  });
639
956
  });
640
957
  }
958
+ function redactAssetRequestUrl(requestUrl) {
959
+ if (!requestUrl) return requestUrl;
960
+ try {
961
+ const segments = new URL$1(requestUrl, `http://${LOOPBACK_HOST}`).pathname.split("/").filter(Boolean);
962
+ if (segments.length >= 1 && secretsEqual(segments[0] ?? "", accessToken)) segments[0] = "<capability>";
963
+ return `/${segments.join("/")}`;
964
+ } catch {
965
+ return "<invalid>";
966
+ }
967
+ }
641
968
  function sendError(res, status, message, details) {
642
- if (!res.headersSent) res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
643
- res.end(JSON.stringify({
969
+ sendJson(res, status, {
644
970
  error: message,
645
971
  ...details
646
- }));
972
+ });
647
973
  }
648
- function sendOk(res, status, message, data) {
974
+ function sendJson(res, status, payload) {
649
975
  if (!res.headersSent) res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
650
- res.end(JSON.stringify({
651
- message,
652
- ...data
653
- }));
976
+ res.end(JSON.stringify(payload));
654
977
  }
655
978
  return {
656
979
  start,
@@ -658,6 +981,23 @@ function createAssetHttpServer(store) {
658
981
  getBaseUrl
659
982
  };
660
983
  }
984
+ function getHeader(req, name) {
985
+ const value = req.headers[name];
986
+ return Array.isArray(value) ? value[0] : value;
987
+ }
988
+ function parseContentLength(req) {
989
+ const value = getHeader(req, "content-length");
990
+ if (value === void 0) return null;
991
+ if (!/^\d+$/.test(value)) return "invalid";
992
+ const parsed = Number(value);
993
+ return Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : "invalid";
994
+ }
995
+ function getStoredAssetBytes(store, excludeHash) {
996
+ return store.list().reduce((total, record) => {
997
+ if (record.hash === excludeHash) return total;
998
+ return Number.isFinite(record.size) && record.size > 0 ? total + record.size : total;
999
+ }, 0);
1000
+ }
661
1001
  //#endregion
662
1002
  //#region src/asset-store.ts
663
1003
  const INDEX_FILENAME = "assets.json";
@@ -819,6 +1159,166 @@ function createAssetStore(options = {}) {
819
1159
  };
820
1160
  }
821
1161
  //#endregion
1162
+ //#region src/extension-registry.ts
1163
+ var ExtensionRegistry = class {
1164
+ #autoActivateGraceMs;
1165
+ #extensions = [];
1166
+ #activeId = null;
1167
+ #autoActivateTimer = null;
1168
+ constructor(autoActivateGraceMs) {
1169
+ this.#autoActivateGraceMs = autoActivateGraceMs;
1170
+ }
1171
+ get size() {
1172
+ return this.#extensions.length;
1173
+ }
1174
+ add(extension) {
1175
+ if (this.#extensions.some(({ id }) => id === extension.id)) throw new Error(`Extension connection already registered: ${extension.id}`);
1176
+ this.#extensions.push(extension);
1177
+ }
1178
+ remove(id) {
1179
+ const index = this.#extensions.findIndex((extension) => extension.id === id);
1180
+ if (index < 0) return null;
1181
+ this.clearAutoActivation();
1182
+ const extension = this.#extensions[index];
1183
+ this.#extensions.splice(index, 1);
1184
+ const wasActive = this.#activeId === id;
1185
+ if (wasActive) this.#activeId = null;
1186
+ return {
1187
+ extension,
1188
+ wasActive
1189
+ };
1190
+ }
1191
+ activate(id) {
1192
+ const target = this.#extensions.find((extension) => extension.id === id);
1193
+ if (!target) return false;
1194
+ const active = this.getActive();
1195
+ if (active && active.id !== target.id && active.origin !== target.origin) return false;
1196
+ this.#activeId = id;
1197
+ return true;
1198
+ }
1199
+ getActive() {
1200
+ return this.#extensions.find((extension) => extension.id === this.#activeId);
1201
+ }
1202
+ getActiveId() {
1203
+ return this.#activeId;
1204
+ }
1205
+ list() {
1206
+ return this.#extensions;
1207
+ }
1208
+ scheduleAutoActivation(onActivated) {
1209
+ this.clearAutoActivation();
1210
+ if (this.#extensions.length !== 1 || this.getActive()) return;
1211
+ const targetId = this.#extensions[0].id;
1212
+ this.#autoActivateTimer = setTimeout(() => {
1213
+ this.#autoActivateTimer = null;
1214
+ if (this.#extensions.length !== 1 || this.getActiveId() || !this.activate(targetId)) return;
1215
+ onActivated(targetId);
1216
+ }, this.#autoActivateGraceMs);
1217
+ unrefTimer$1(this.#autoActivateTimer);
1218
+ }
1219
+ clearAutoActivation() {
1220
+ if (!this.#autoActivateTimer) return;
1221
+ clearTimeout(this.#autoActivateTimer);
1222
+ this.#autoActivateTimer = null;
1223
+ }
1224
+ dispose() {
1225
+ this.clearAutoActivation();
1226
+ }
1227
+ };
1228
+ function unrefTimer$1(timer) {
1229
+ if (typeof timer !== "object" || timer === null) return;
1230
+ const handle = timer;
1231
+ if (typeof handle.unref === "function") handle.unref();
1232
+ }
1233
+ //#endregion
1234
+ //#region src/extension-socket.ts
1235
+ function attachExtensionSocket(ws, options) {
1236
+ const extension = {
1237
+ id: options.createId(),
1238
+ origin: options.origin.toLowerCase(),
1239
+ ws
1240
+ };
1241
+ options.registry.add(extension);
1242
+ options.onConnected?.(extension.id);
1243
+ const registered = {
1244
+ id: extension.id,
1245
+ type: "registered"
1246
+ };
1247
+ ws.send(JSON.stringify(registered));
1248
+ options.onStateChange();
1249
+ scheduleAutoActivation(options);
1250
+ ws.on("message", (raw, isBinary) => {
1251
+ if (isBinary) {
1252
+ options.onProtocolWarning?.({
1253
+ extensionId: extension.id,
1254
+ kind: "binary"
1255
+ });
1256
+ return;
1257
+ }
1258
+ let parsedJson;
1259
+ try {
1260
+ parsedJson = JSON.parse(rawDataToBuffer(raw).toString("utf-8"));
1261
+ } catch (error) {
1262
+ options.onProtocolWarning?.({
1263
+ error,
1264
+ extensionId: extension.id,
1265
+ kind: "json"
1266
+ });
1267
+ return;
1268
+ }
1269
+ const parseResult = MessageFromExtensionSchema.safeParse(parsedJson);
1270
+ if (!parseResult.success) {
1271
+ options.onProtocolWarning?.({
1272
+ error: parseResult.error.flatten(),
1273
+ extensionId: extension.id,
1274
+ kind: "schema"
1275
+ });
1276
+ return;
1277
+ }
1278
+ const message = parseResult.data;
1279
+ switch (message.type) {
1280
+ case "activate":
1281
+ if (options.registry.activate(extension.id)) {
1282
+ options.onActivated?.(extension.id);
1283
+ options.onStateChange();
1284
+ scheduleAutoActivation(options);
1285
+ } else {
1286
+ const activeExtensionId = options.registry.getActiveId();
1287
+ if (activeExtensionId) options.onActivationRejected?.(extension.id, activeExtensionId);
1288
+ }
1289
+ break;
1290
+ case "toolResult":
1291
+ if (message.error !== void 0) options.onToolError(message.id, extension.id, message.error);
1292
+ else options.onToolResult(message.id, extension.id, message.payload);
1293
+ break;
1294
+ case "ping": break;
1295
+ }
1296
+ });
1297
+ ws.on("error", (error) => {
1298
+ options.onSocketError?.(extension.id, error);
1299
+ });
1300
+ ws.once("close", () => {
1301
+ const removed = options.registry.remove(extension.id);
1302
+ if (!removed) return;
1303
+ options.onDisconnected?.(extension.id, removed.wasActive);
1304
+ options.onStateChange();
1305
+ scheduleAutoActivation(options);
1306
+ });
1307
+ return extension;
1308
+ }
1309
+ function scheduleAutoActivation(options) {
1310
+ options.registry.scheduleAutoActivation((extensionId) => {
1311
+ options.onAutoActivated?.(extensionId);
1312
+ options.onStateChange();
1313
+ });
1314
+ }
1315
+ function rawDataToBuffer(raw) {
1316
+ if (typeof raw === "string") return Buffer.from(raw);
1317
+ if (Buffer.isBuffer(raw)) return raw;
1318
+ if (raw instanceof ArrayBuffer) return Buffer.from(raw);
1319
+ return Buffer.concat(raw);
1320
+ }
1321
+ //#endregion
822
1322
  //#region src/instructions.md?raw
823
1323
  var instructions_default = "You are connected to a Figma design file via TemPad Dev MCP.\n\nTreat tool outputs as design facts. Refactor only to match the user’s repo conventions; do not invent key style values.\n\nRules:\n\n- Never output any `data-hint-*` attributes from tool outputs (hints only).\n- If `get_code` warns `depth-cap`, keep the returned parent code as composition evidence and use returned `data-hint-id` values to choose narrower `get_code` follow-ups.\n- If `get_code` warns `shell`, read the inline code comment for omitted direct child ids, then call `get_code` for those ids in order and fill the results back into the returned shell.\n- Use `get_structure` only to resolve layout/overlap uncertainty; do not derive numeric values from images.\n- Tokens: `get_code.tokens` keys are canonical names (`--...`). Multi‑mode values use `${collectionName}:${modeName}`. Nodes may hint per-node overrides via `data-hint-variable-mode=\"Collection=Mode;...\"`.\n- Vectors: `vectorMode=smart` is the default. Treat the emitted markup as the source of truth for the current response; vector code is emitted as `<svg data-src=\"...\">` placeholders, but if asset upload fails after export the tool may inline the SVG as a fallback to preserve source of truth.\n- Themeable vectors: `themeable=true` means the SVG can safely adopt one contextual color channel. In `smart` mode, that color is typically already evidenced on the emitted `svg` root markup for the placeholder. It does not mean the SVG exposes multiple independent color parameters.\n- Assets: download bytes via `asset.url`. Asset resources are not exposed via MCP `resources/read`. Use `asset.themeable` only when an SVG still needs repo asset handling after you account for the Host app's vector policy.\n";
824
1324
  //#endregion
@@ -847,18 +1347,34 @@ function register(extensionId, timeout) {
847
1347
  requestId
848
1348
  };
849
1349
  }
850
- function resolve(requestId, payload) {
1350
+ function resolve(requestId, extensionId, payload) {
851
1351
  const call = pendingCalls.get(requestId);
852
1352
  if (call) {
1353
+ if (call.extensionId !== extensionId) {
1354
+ log.warn({
1355
+ reqId: requestId,
1356
+ expectedExtId: call.extensionId,
1357
+ receivedExtId: extensionId
1358
+ }, "Ignored tool result from the wrong extension.");
1359
+ return;
1360
+ }
853
1361
  const { timer, resolve: finish } = call;
854
1362
  clearTimeout(timer);
855
1363
  finish(payload);
856
1364
  pendingCalls.delete(requestId);
857
1365
  } else log.warn({ reqId: requestId }, "Received result for unknown/timed-out call.");
858
1366
  }
859
- function reject(requestId, error) {
1367
+ function reject(requestId, extensionId, error) {
860
1368
  const call = pendingCalls.get(requestId);
861
1369
  if (call) {
1370
+ if (call.extensionId !== extensionId) {
1371
+ log.warn({
1372
+ reqId: requestId,
1373
+ expectedExtId: call.extensionId,
1374
+ receivedExtId: extensionId
1375
+ }, "Ignored tool error from the wrong extension.");
1376
+ return;
1377
+ }
862
1378
  const { timer, reject: fail } = call;
863
1379
  clearTimeout(timer);
864
1380
  fail(error);
@@ -898,6 +1414,7 @@ const CONNECTIVITY_ERROR_CODES = /* @__PURE__ */ new Set([
898
1414
  TEMPAD_MCP_ERROR_CODES.TRANSPORT_NOT_CONNECTED
899
1415
  ]);
900
1416
  const SELECTION_ERROR_CODES = /* @__PURE__ */ new Set([TEMPAD_MCP_ERROR_CODES.INVALID_SELECTION, TEMPAD_MCP_ERROR_CODES.NODE_NOT_VISIBLE]);
1417
+ const KNOWN_ERROR_CODES = new Set(Object.values(TEMPAD_MCP_ERROR_CODES));
901
1418
  const CONNECTIVITY_TROUBLESHOOTING_LINES = [
902
1419
  "Troubleshooting:",
903
1420
  "- In Figma, open TemPad Dev panel and enable the MCP server in Preferences → Agent integration.",
@@ -957,9 +1474,12 @@ const TOOL_DEFS = [
957
1474
  ];
958
1475
  function extractToolErrorCode(error) {
959
1476
  const code = getRecordProperty$1(error, "code");
960
- if (typeof code === "string") return code;
1477
+ if (isTempadMcpErrorCode(code)) return code;
961
1478
  const causeCode = getRecordProperty$1(getRecordProperty$1(error, "cause"), "code");
962
- if (typeof causeCode === "string") return causeCode;
1479
+ if (isTempadMcpErrorCode(causeCode)) return causeCode;
1480
+ }
1481
+ function isTempadMcpErrorCode(value) {
1482
+ return typeof value === "string" && KNOWN_ERROR_CODES.has(value);
963
1483
  }
964
1484
  function extractToolErrorMessage(error) {
965
1485
  if (error instanceof Error) return error.message || "Unknown error occurred.";
@@ -1067,14 +1587,68 @@ function getBudgetRetryGuidance(toolName) {
1067
1587
  }
1068
1588
  }
1069
1589
  //#endregion
1590
+ //#region src/websocket-server.ts
1591
+ async function startExtensionWebSocketServer({ maxPayloadBytes, maxConnections, originPolicy, portCandidates, onPortInUse, onConnectionLimit, onRejectedHandshake }) {
1592
+ for (const candidate of portCandidates) {
1593
+ const server = new WebSocketServer({
1594
+ host: "127.0.0.1",
1595
+ port: candidate,
1596
+ maxPayload: maxPayloadBytes,
1597
+ verifyClient: (info) => {
1598
+ if (server.clients.size >= maxConnections) {
1599
+ onConnectionLimit?.(maxConnections);
1600
+ return false;
1601
+ }
1602
+ const allowed = isAllowedWebSocketRequest(info.origin, info.req.url, originPolicy);
1603
+ if (!allowed) onRejectedHandshake?.(info.origin, info.req.url);
1604
+ return allowed;
1605
+ }
1606
+ });
1607
+ try {
1608
+ await waitForListening(server);
1609
+ return {
1610
+ server,
1611
+ port: resolveListeningPort(server, candidate)
1612
+ };
1613
+ } catch (error) {
1614
+ server.close();
1615
+ const errno = error;
1616
+ if (errno.code === "EADDRINUSE") {
1617
+ onPortInUse?.(candidate);
1618
+ continue;
1619
+ }
1620
+ throw errno;
1621
+ }
1622
+ }
1623
+ throw new Error(`Unable to start WebSocket server on candidate ports: ${portCandidates.join(", ")}.`);
1624
+ }
1625
+ function waitForListening(server) {
1626
+ return new Promise((resolve, reject) => {
1627
+ const onError = (error) => {
1628
+ server.off("listening", onListening);
1629
+ reject(error);
1630
+ };
1631
+ const onListening = () => {
1632
+ server.off("error", onError);
1633
+ resolve();
1634
+ };
1635
+ server.once("error", onError);
1636
+ server.once("listening", onListening);
1637
+ });
1638
+ }
1639
+ function resolveListeningPort(server, candidate) {
1640
+ const address = server.address();
1641
+ return address && typeof address === "object" ? address.port : candidate;
1642
+ }
1643
+ //#endregion
1070
1644
  //#region src/hub.ts
1071
1645
  const SHUTDOWN_TIMEOUT = 2e3;
1072
1646
  const SOCKET_PROBE_TIMEOUT_MS = 300;
1073
- const { wsPortCandidates, toolTimeoutMs, maxPayloadBytes, autoActivateGraceMs, assetTtlMs } = getMcpServerConfig();
1647
+ const { wsPortCandidates, toolTimeoutMs, maxPayloadBytes, maxExtensionConnections, autoActivateGraceMs, assetTtlMs, allowedExtensionOrigins } = getMcpServerConfig();
1648
+ const extensionOriginPolicy = createExtensionOriginPolicy(allowedExtensionOrigins);
1074
1649
  log.info({ version: PACKAGE_VERSION }, "TemPad MCP Hub starting...");
1075
- const extensions = [];
1650
+ const extensionRegistry = new ExtensionRegistry(autoActivateGraceMs);
1076
1651
  let consumerCount = 0;
1077
- let autoActivateTimer = null;
1078
1652
  let selectedWsPort = 0;
1079
1653
  let releaseHubLock = null;
1080
1654
  let shuttingDown = false;
@@ -1207,7 +1781,7 @@ function getToolDefinition(name) {
1207
1781
  return TOOL_BY_NAME[name];
1208
1782
  }
1209
1783
  const assetStore = createAssetStore();
1210
- const assetHttpServer = createAssetHttpServer(assetStore);
1784
+ const assetHttpServer = createAssetHttpServer(assetStore, { authorizeExtensionOrigin: (origin) => extensionRegistry.getActive()?.origin === origin.toLowerCase() });
1211
1785
  function scheduleAssetCleanup() {
1212
1786
  if (assetTtlMs <= 0) {
1213
1787
  log.info("Asset TTL cleanup disabled (TEMPAD_MCP_ASSET_TTL_MS=0).");
@@ -1256,7 +1830,8 @@ function buildAssetDescriptor(record) {
1256
1830
  }
1257
1831
  function createMcpServer() {
1258
1832
  const mcp = new McpServer({
1259
- name: "tempad-dev-mcp",
1833
+ name: "tempad-dev",
1834
+ title: "TemPad Dev",
1260
1835
  version: PACKAGE_VERSION
1261
1836
  }, { instructions: instructions_default });
1262
1837
  const registered = [];
@@ -1279,7 +1854,7 @@ function registerProxiedTool(mcp, tool) {
1279
1854
  let requestId;
1280
1855
  try {
1281
1856
  const parsedArgs = schema.parse(args);
1282
- const activeExt = extensions.find((e) => e.active);
1857
+ const activeExt = extensionRegistry.getActive();
1283
1858
  if (!activeExt) throw createCodedError(TEMPAD_MCP_ERROR_CODES.NO_ACTIVE_EXTENSION, "No active TemPad Dev extension available.");
1284
1859
  const registration = register(activeExt.id, toolTimeoutMs);
1285
1860
  requestId = registration.requestId;
@@ -1377,33 +1952,6 @@ async function handleGetAssets({ hashes }) {
1377
1952
  missing: unique.filter((hash) => !found.has(hash))
1378
1953
  }));
1379
1954
  }
1380
- function getActiveId() {
1381
- return extensions.find((e) => e.active)?.id ?? null;
1382
- }
1383
- function setActive(targetId) {
1384
- extensions.forEach((e) => {
1385
- e.active = targetId !== null && e.id === targetId;
1386
- });
1387
- }
1388
- function clearAutoActivateTimer() {
1389
- if (autoActivateTimer) {
1390
- clearTimeout(autoActivateTimer);
1391
- autoActivateTimer = null;
1392
- }
1393
- }
1394
- function scheduleAutoActivate() {
1395
- clearAutoActivateTimer();
1396
- if (extensions.length !== 1 || getActiveId()) return;
1397
- const target = extensions[0];
1398
- autoActivateTimer = setTimeout(() => {
1399
- autoActivateTimer = null;
1400
- if (extensions.length === 1 && !getActiveId()) {
1401
- setActive(target.id);
1402
- log.info({ id: target.id }, "Auto-activated sole extension after grace period.");
1403
- broadcastState();
1404
- }
1405
- }, autoActivateGraceMs);
1406
- }
1407
1955
  function unrefTimer(timer) {
1408
1956
  if (typeof timer === "object" && timer !== null) {
1409
1957
  const handle = timer;
@@ -1411,24 +1959,18 @@ function unrefTimer(timer) {
1411
1959
  }
1412
1960
  }
1413
1961
  function broadcastState() {
1414
- const activeId = getActiveId();
1962
+ const activeId = extensionRegistry.getActiveId();
1415
1963
  const message = {
1416
1964
  type: "state",
1417
1965
  activeId,
1418
1966
  assetServerUrl: assetHttpServer.getBaseUrl()
1419
1967
  };
1420
- extensions.forEach((ext) => ext.ws.send(JSON.stringify(message)));
1968
+ extensionRegistry.list().forEach((ext) => ext.ws.send(JSON.stringify(message)));
1421
1969
  log.debug({
1422
1970
  activeId,
1423
- count: extensions.length
1971
+ count: extensionRegistry.size
1424
1972
  }, "Broadcasted state.");
1425
1973
  }
1426
- function rawDataToBuffer(raw) {
1427
- if (typeof raw === "string") return Buffer.from(raw);
1428
- if (Buffer.isBuffer(raw)) return raw;
1429
- if (raw instanceof ArrayBuffer) return Buffer.from(raw);
1430
- return Buffer.concat(raw);
1431
- }
1432
1974
  function shutdown() {
1433
1975
  if (shuttingDown) return;
1434
1976
  shuttingDown = true;
@@ -1440,6 +1982,7 @@ function shutdown() {
1440
1982
  });
1441
1983
  consumerSessions.clear();
1442
1984
  assetStore.flush();
1985
+ extensionRegistry.dispose();
1443
1986
  assetHttpServer.stop();
1444
1987
  netServer.close(() => log.info("Net server closed."));
1445
1988
  wss?.close(() => log.info("WebSocket server closed."));
@@ -1515,40 +2058,24 @@ function listenConsumerSocket() {
1515
2058
  });
1516
2059
  }
1517
2060
  async function startWebSocketServer() {
1518
- for (const candidate of wsPortCandidates) {
1519
- const server = new WebSocketServer({
1520
- host: "127.0.0.1",
1521
- port: candidate,
1522
- maxPayload: maxPayloadBytes
1523
- });
1524
- try {
1525
- await new Promise((resolve, reject) => {
1526
- const onError = (err) => {
1527
- server.off("listening", onListening);
1528
- reject(err);
1529
- };
1530
- const onListening = () => {
1531
- server.off("error", onError);
1532
- resolve();
1533
- };
1534
- server.once("error", onError);
1535
- server.once("listening", onListening);
1536
- });
1537
- return {
1538
- server,
1539
- port: candidate
1540
- };
1541
- } catch (err) {
1542
- server.close();
1543
- const errno = err;
1544
- if (errno.code === "EADDRINUSE") {
1545
- log.warn({ port: candidate }, "WebSocket port in use, trying next candidate.");
1546
- continue;
1547
- }
1548
- throw errno;
2061
+ return startExtensionWebSocketServer({
2062
+ maxConnections: maxExtensionConnections,
2063
+ maxPayloadBytes,
2064
+ originPolicy: extensionOriginPolicy,
2065
+ portCandidates: wsPortCandidates,
2066
+ onPortInUse: (port) => {
2067
+ log.warn({ port }, "WebSocket port in use, trying next candidate.");
2068
+ },
2069
+ onConnectionLimit: (limit) => {
2070
+ log.warn({ limit }, "Rejected WebSocket handshake at the extension connection limit.");
2071
+ },
2072
+ onRejectedHandshake: (origin, path) => {
2073
+ log.warn({
2074
+ origin: origin || "<missing>",
2075
+ path: path || "<missing>"
2076
+ }, "Rejected unauthorized WebSocket handshake.");
1549
2077
  }
1550
- }
1551
- throw new Error(`Unable to start WebSocket server on candidate ports: ${wsPortCandidates.join(", ")}.`);
2078
+ });
1552
2079
  }
1553
2080
  async function startHubRuntime() {
1554
2081
  await initializeHubRuntime();
@@ -1573,84 +2100,68 @@ activeWss.on("error", (err) => {
1573
2100
  log.error({ err }, "WebSocket server critical error. Exiting.");
1574
2101
  process.exit(1);
1575
2102
  });
1576
- activeWss.on("connection", (ws) => {
1577
- const ext = {
1578
- id: nanoid(),
1579
- ws,
1580
- active: false
1581
- };
1582
- extensions.push(ext);
1583
- log.info({ id: ext.id }, `Extension connected. Total: ${extensions.length}`);
1584
- const message = {
1585
- type: "registered",
1586
- id: ext.id
1587
- };
1588
- ws.send(JSON.stringify(message));
1589
- broadcastState();
1590
- scheduleAutoActivate();
1591
- ws.on("message", (raw, isBinary) => {
1592
- if (isBinary) {
1593
- log.warn({ extId: ext.id }, "Unexpected binary message received.");
1594
- return;
1595
- }
1596
- const messageBuffer = rawDataToBuffer(raw);
1597
- let parsedJson;
1598
- try {
1599
- parsedJson = JSON.parse(messageBuffer.toString("utf-8"));
1600
- } catch (e) {
2103
+ activeWss.on("connection", (ws, request) => {
2104
+ attachExtensionSocket(ws, {
2105
+ createId: randomUUID,
2106
+ origin: request.headers.origin ?? "",
2107
+ registry: extensionRegistry,
2108
+ onActivationRejected: (extensionId, activeExtensionId) => {
1601
2109
  log.warn({
1602
- err: e,
1603
- extId: ext.id
2110
+ activeId: activeExtensionId,
2111
+ id: extensionId
2112
+ }, "Rejected activation from a different extension Origin.");
2113
+ },
2114
+ onActivated: (extensionId) => {
2115
+ log.info({ id: extensionId }, "Extension activated.");
2116
+ },
2117
+ onAutoActivated: (extensionId) => {
2118
+ log.info({ id: extensionId }, "Auto-activated sole extension after grace period.");
2119
+ },
2120
+ onConnected: (extensionId) => {
2121
+ log.info({ id: extensionId }, `Extension connected. Total: ${extensionRegistry.size}`);
2122
+ },
2123
+ onDisconnected: (extensionId, wasActive) => {
2124
+ log.info({ id: extensionId }, `Extension disconnected. Remaining: ${extensionRegistry.size}`);
2125
+ cleanupForExtension(extensionId);
2126
+ if (wasActive) log.warn({ id: extensionId }, "Active extension disconnected.");
2127
+ },
2128
+ onProtocolWarning: (warning) => {
2129
+ if (warning.kind === "binary") log.warn({ extId: warning.extensionId }, "Unexpected binary message received.");
2130
+ else if (warning.kind === "json") log.warn({
2131
+ err: warning.error,
2132
+ extId: warning.extensionId
1604
2133
  }, "Failed to parse message.");
1605
- return;
1606
- }
1607
- const parseResult = MessageFromExtensionSchema.safeParse(parsedJson);
1608
- if (!parseResult.success) {
1609
- log.warn({
1610
- error: parseResult.error.flatten(),
1611
- extId: ext.id
2134
+ else log.warn({
2135
+ error: warning.error,
2136
+ extId: warning.extensionId
1612
2137
  }, "Invalid message shape.");
1613
- return;
1614
- }
1615
- const msg = parseResult.data;
1616
- switch (msg.type) {
1617
- case "activate":
1618
- setActive(ext.id);
1619
- log.info({ id: ext.id }, "Extension activated.");
1620
- broadcastState();
1621
- scheduleAutoActivate();
1622
- break;
1623
- case "toolResult": {
1624
- const { id, payload, error } = msg;
1625
- if (error) {
1626
- const normalized = coerceToolError(error);
1627
- log.warn({
1628
- toolReq: id,
1629
- extId: ext.id,
1630
- code: getRecordProperty(normalized, "code"),
1631
- message: normalized.message
1632
- }, "Received tool error from extension.");
1633
- reject(id, normalized);
1634
- } else resolve(id, payload);
1635
- break;
1636
- }
1637
- case "ping": break;
1638
- }
1639
- });
1640
- ws.on("close", () => {
1641
- const index = extensions.findIndex((e) => e.id === ext.id);
1642
- if (index > -1) extensions.splice(index, 1);
1643
- log.info({ id: ext.id }, `Extension disconnected. Remaining: ${extensions.length}`);
1644
- cleanupForExtension(ext.id);
1645
- if (ext.active) {
1646
- log.warn({ id: ext.id }, "Active extension disconnected.");
1647
- setActive(null);
2138
+ },
2139
+ onSocketError: (extensionId, error) => {
2140
+ log.warn({
2141
+ err: error,
2142
+ extId: extensionId
2143
+ }, "Extension WebSocket error.");
2144
+ },
2145
+ onStateChange: broadcastState,
2146
+ onToolError: (requestId, extensionId, error) => {
2147
+ const normalized = coerceToolError(error);
2148
+ log.warn({
2149
+ toolReq: requestId,
2150
+ extId: extensionId,
2151
+ code: getRecordProperty(normalized, "code"),
2152
+ message: normalized.message
2153
+ }, "Received tool error from extension.");
2154
+ reject(requestId, extensionId, normalized);
2155
+ },
2156
+ onToolResult: (requestId, extensionId, payload) => {
2157
+ resolve(requestId, extensionId, payload);
1648
2158
  }
1649
- broadcastState();
1650
- scheduleAutoActivate();
1651
2159
  });
1652
2160
  });
1653
- log.info({ port: selectedWsPort }, "WebSocket server ready.");
2161
+ log.info({
2162
+ port: selectedWsPort,
2163
+ extensionOriginPolicy: extensionOriginPolicy.mode
2164
+ }, "WebSocket server ready.");
1654
2165
  process.on("SIGINT", shutdown);
1655
2166
  process.on("SIGTERM", shutdown);
1656
2167
  //#endregion