@mastra/hono 1.7.21-alpha.2 → 1.7.21-alpha.4

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/index.js CHANGED
@@ -89,7 +89,162 @@ function createAuthMiddleware({ mastra, requiresAuth = true }) {
89
89
  };
90
90
  }
91
91
  //#endregion
92
+ //#region src/browser-stream/upgrade-tickets.ts
93
+ const TICKET_BYTES = 32;
94
+ /**
95
+ * How long an issued ticket stays valid. A ticket is minted immediately before
96
+ * the socket is opened, so this only has to cover the round trip plus the
97
+ * handshake — short enough that a ticket leaked from a log is useless by the
98
+ * time anyone can act on it.
99
+ */
100
+ const UPGRADE_TICKET_TTL_MS = 3e4;
101
+ /**
102
+ * Ceiling on tracked per-agent issuance counters, so the limiter can't grow
103
+ * without bound as agent ids are invented. Counters are evicted oldest first.
104
+ */
105
+ const MAX_TRACKED_AGENTS = 500;
106
+ /** 256 bits of base64url, so the ticket can't be guessed or enumerated. */
107
+ function createTicketValue() {
108
+ const bytes = new Uint8Array(TICKET_BYTES);
109
+ globalThis.crypto.getRandomValues(bytes);
110
+ return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
111
+ }
112
+ /**
113
+ * Short-lived, single-use credentials for browser WebSocket upgrades.
114
+ *
115
+ * A browser cannot set an `Authorization` header on a WebSocket handshake, so a
116
+ * deployment that authenticates with a header token would otherwise have to put
117
+ * that reusable token in the handshake URL, where proxies and access logs can
118
+ * retain it. Instead the client asks an authenticated HTTP route for a ticket,
119
+ * and the ticket — worthless once spent, and scoped to one agent and thread —
120
+ * travels in the URL instead.
121
+ *
122
+ * In-process, like the `ViewerRegistry` and the browser sessions it serves: a
123
+ * screencast is bound to the process holding the browser, so a ticket store
124
+ * shared across replicas would buy nothing. A ticket presented to a different
125
+ * replica fails for the same reason the stream itself would.
126
+ *
127
+ * Issuance is bounded so the mint endpoint can't be turned into memory or CPU
128
+ * exhaustion: tickets that are never spent live at most one TTL, a full store
129
+ * rejects instead of growing, and each agent has a request allowance. Expiry is
130
+ * swept from the front of the insertion-ordered map, so cleanup costs the
131
+ * number of entries actually expired rather than a scan of every outstanding
132
+ * ticket per request.
133
+ */
134
+ var UpgradeTicketStore = class {
135
+ #tickets = /* @__PURE__ */ new Map();
136
+ #issuance = /* @__PURE__ */ new Map();
137
+ #now;
138
+ constructor(now = () => Date.now()) {
139
+ this.#now = now;
140
+ }
141
+ /**
142
+ * Issue a ticket bound to one agent and thread. Returns `{ ok: false }` when
143
+ * the agent exceeded its allowance or the store is at capacity.
144
+ */
145
+ issue(agentId, threadId, ttlMs = UPGRADE_TICKET_TTL_MS) {
146
+ const now = this.#now();
147
+ this.#prune(now);
148
+ if (this.#tickets.size >= 500) return {
149
+ ok: false,
150
+ reason: "capacity"
151
+ };
152
+ const window = this.#issuance.get(agentId);
153
+ if (!window || now - window.windowStart >= 6e4) this.#trackIssuance(agentId, {
154
+ windowStart: now,
155
+ count: 0
156
+ });
157
+ else if (window.count >= 30) return {
158
+ ok: false,
159
+ reason: "rate-limited"
160
+ };
161
+ this.#issuance.get(agentId).count += 1;
162
+ const ticket = createTicketValue();
163
+ this.#tickets.set(ticket, {
164
+ agentId,
165
+ threadId,
166
+ expiresAt: now + ttlMs
167
+ });
168
+ return {
169
+ ok: true,
170
+ ticket,
171
+ expiresIn: Math.ceil(ttlMs / 1e3)
172
+ };
173
+ }
174
+ /**
175
+ * Spend a ticket. Returns `true` only when the ticket is unexpired and was
176
+ * issued for this exact agent and thread, in which case it is consumed and a
177
+ * second presentation fails.
178
+ */
179
+ consume(ticket, agentId, threadId) {
180
+ const entry = this.#tickets.get(ticket);
181
+ if (!entry) return false;
182
+ if (entry.expiresAt <= this.#now()) return false;
183
+ if (entry.agentId !== agentId) return false;
184
+ if ((entry.threadId ?? void 0) !== (threadId ?? void 0)) return false;
185
+ this.#tickets.delete(ticket);
186
+ return true;
187
+ }
188
+ /**
189
+ * Drop expired tickets from the front of the insertion-ordered map. Tickets
190
+ * are inserted in issue order and share a TTL, so the entries after the first
191
+ * live one are live too and the sweep can stop there.
192
+ */
193
+ #prune(now) {
194
+ for (const [ticket, entry] of this.#tickets) {
195
+ if (entry.expiresAt > now) break;
196
+ this.#tickets.delete(ticket);
197
+ }
198
+ }
199
+ /** Record an issuance window, evicting the oldest counter when at the cap. */
200
+ #trackIssuance(agentId, window) {
201
+ this.#issuance.delete(agentId);
202
+ this.#issuance.set(agentId, window);
203
+ if (this.#issuance.size > MAX_TRACKED_AGENTS) {
204
+ const oldest = this.#issuance.keys().next().value;
205
+ if (oldest !== void 0) this.#issuance.delete(oldest);
206
+ }
207
+ }
208
+ };
209
+ //#endregion
92
210
  //#region src/browser-stream/index.ts
211
+ const TICKET_BODY_MAX_BYTES = 4 * 1024;
212
+ /**
213
+ * Resolve an `allowedOrigins` value against the request's `Origin` header.
214
+ *
215
+ * Mirrors Hono's `cors.origin` semantics so the same config value means the same
216
+ * thing on the upgrade as it does on the HTTP routes: `'*'` allows everything,
217
+ * array entries match literally, and a callback is only an approval when it
218
+ * returns the request's own origin (the value Hono would echo back) or `'*'`.
219
+ */
220
+ async function isOriginAllowed(allowedOrigins, origin, c) {
221
+ if (Array.isArray(allowedOrigins)) return allowedOrigins.includes(origin);
222
+ if (typeof allowedOrigins === "function") {
223
+ const allowed = await allowedOrigins(origin, c);
224
+ return allowed === origin || allowed === "*";
225
+ }
226
+ return allowedOrigins === "*" || allowedOrigins === origin;
227
+ }
228
+ /**
229
+ * Is the `Origin` header the server's own origin?
230
+ *
231
+ * A Studio served by this server connects back to the same host, and operators
232
+ * don't add their own origin to a CORS allowlist because same-origin requests
233
+ * never needed CORS. Comparing hosts (rather than scheme + host) keeps that
234
+ * working behind TLS-terminating proxies, where the server sees `http` while the
235
+ * browser sends `https`.
236
+ */
237
+ function isSameOrigin(origin, requestHost) {
238
+ if (!requestHost) return false;
239
+ let originHost;
240
+ try {
241
+ originHost = new URL(origin).host;
242
+ } catch {
243
+ return false;
244
+ }
245
+ const host = (requestHost.split(",")[0] ?? "").trim();
246
+ return originHost !== "" && originHost.toLowerCase() === host.toLowerCase();
247
+ }
93
248
  /**
94
249
  * Set up WebSocket-based browser stream endpoint for real-time screencast viewing.
95
250
  *
@@ -99,6 +254,17 @@ function createAuthMiddleware({ mastra, requiresAuth = true }) {
99
254
  * - Broadcasts frames to all connected viewers
100
255
  * - Stops screencast when last viewer disconnects
101
256
  *
257
+ * All routes are authenticated with the server's auth configuration. Browsers
258
+ * cannot attach an `Authorization` header to a WebSocket upgrade, so
259
+ * session-cookie providers authenticate from the upgrade request's cookies.
260
+ * Clients that authenticate with a header token instead request a short-lived,
261
+ * single-use ticket from `POST ${apiPrefix}/agents/:agentId/browser/stream-ticket`
262
+ * and pass it to the upgrade as `?ticket=`, which keeps the reusable credential
263
+ * out of the URL. Non-browser clients can pass the token as the `apiKey` query
264
+ * parameter — use a short-lived token, since a URL can be retained in proxy and
265
+ * access logs, and prefer the `Authorization` header on the HTTP routes where the
266
+ * client can set one.
267
+ *
102
268
  * **Note**: Requires `ws` package to be installed. If not available, returns null
103
269
  * and logs a warning. Browser streaming will be disabled but everything else works.
104
270
  *
@@ -114,6 +280,7 @@ function createAuthMiddleware({ mastra, requiresAuth = true }) {
114
280
  *
115
281
  * const app = new Hono();
116
282
  * const browserStream = await setupBrowserStream(app, {
283
+ * mastra,
117
284
  * getToolset: (agentId) => browserToolsets.get(agentId),
118
285
  * });
119
286
  *
@@ -136,7 +303,24 @@ async function setupBrowserStream(app, config) {
136
303
  const registry = new ViewerRegistry();
137
304
  const rawPrefix = config.apiPrefix ?? "/api";
138
305
  const apiPrefix = (rawPrefix.endsWith("/") ? rawPrefix.slice(0, -1) : rawPrefix) || "/api";
139
- app.get("/browser/:agentId/stream", upgradeWebSocket((c) => {
306
+ const authenticate = createAuthMiddleware({ mastra: config.mastra });
307
+ const upgradeTickets = new UpgradeTicketStore();
308
+ const authorizeUpgrade = async (c, next) => {
309
+ const ticket = c.req.query("ticket");
310
+ if (!ticket) return authenticate(c, next);
311
+ const agentId = c.req.param("agentId");
312
+ if (!upgradeTickets.consume(ticket, agentId, c.req.query("threadId"))) return c.json({ error: "Invalid or expired upgrade ticket" }, 401);
313
+ return next();
314
+ };
315
+ const allowedOrigins = config.allowedOrigins;
316
+ const checkOrigin = async (c, next) => {
317
+ const origin = c.req.header("origin");
318
+ if (!allowedOrigins || !origin) return next();
319
+ if (isSameOrigin(origin, c.req.header("x-forwarded-host") ?? c.req.header("host"))) return next();
320
+ if (!await isOriginAllowed(allowedOrigins, origin, c)) return c.text("Forbidden", 403);
321
+ return next();
322
+ };
323
+ app.get("/browser/:agentId/stream", checkOrigin, authorizeUpgrade, upgradeWebSocket((c) => {
140
324
  const agentId = c.req.param("agentId");
141
325
  const threadId = c.req.query("threadId");
142
326
  const viewerKey = threadId ? `${agentId}:${threadId}` : agentId;
@@ -158,7 +342,29 @@ async function setupBrowserStream(app, config) {
158
342
  }
159
343
  };
160
344
  }));
161
- app.get(`${apiPrefix}/agents/:agentId/browser/session`, async (c) => {
345
+ const ticketBodyLimit = bodyLimit({
346
+ maxSize: TICKET_BODY_MAX_BYTES,
347
+ onError: (c) => c.json({ error: "Request body too large" }, 413)
348
+ });
349
+ app.post(`${apiPrefix}/agents/:agentId/browser/stream-ticket`, authenticate, ticketBodyLimit, async (c) => {
350
+ const agentId = c.req.param("agentId");
351
+ if (!agentId) return c.json({ error: "Agent ID is required" }, 400);
352
+ let threadId = c.req.query("threadId");
353
+ try {
354
+ const body = await c.req.json();
355
+ if (!threadId && typeof body?.threadId === "string") threadId = body.threadId;
356
+ } catch {}
357
+ const issued = upgradeTickets.issue(agentId, threadId);
358
+ if (!issued.ok) {
359
+ const error = issued.reason === "capacity" ? "Too many outstanding browser stream upgrade tickets" : "Too many browser stream upgrade tickets requested";
360
+ return c.json({ error }, 429);
361
+ }
362
+ return c.json({
363
+ ticket: issued.ticket,
364
+ expiresIn: issued.expiresIn
365
+ });
366
+ });
367
+ app.get(`${apiPrefix}/agents/:agentId/browser/session`, authenticate, async (c) => {
162
368
  const agentId = c.req.param("agentId");
163
369
  if (!agentId) return c.json({ error: "Agent ID is required" }, 400);
164
370
  const threadId = c.req.query("threadId");
@@ -173,7 +379,7 @@ async function setupBrowserStream(app, config) {
173
379
  screencastAvailable: true
174
380
  });
175
381
  });
176
- app.post(`${apiPrefix}/agents/:agentId/browser/close`, async (c) => {
382
+ app.post(`${apiPrefix}/agents/:agentId/browser/close`, authenticate, ticketBodyLimit, async (c) => {
177
383
  const agentId = c.req.param("agentId");
178
384
  if (!agentId) return c.json({ error: "Agent ID is required" }, 400);
179
385
  const toolset = await config.getToolset(agentId);