@tangle-network/agent-app 0.51.16 → 0.52.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.
@@ -1,63 +1,13 @@
1
1
  /**
2
- * `/turn-stream` — shared durable turn replay/broadcast/lock on a Cloudflare
3
- * Durable Object (issue #221): the graduation of `createChatTurnRoutes`'
4
- * `turnStore` seam from "bring your own DO" to a real implementation, plus
5
- * the dual-scope single-flight turn lock and the live-viewer WebSocket
6
- * channel every fleet app was hand-rolling.
7
- *
8
- * Subpath-only and server-only (like `/chat-routes`): never re-exported from
9
- * the root barrel, never reachable from a client bundle. Cloudflare is
10
- * STRUCTURAL throughout — no `cloudflare:workers` import; a product binds
11
- * the DO by re-exporting {@link TurnStreamDO} from its worker entry and
12
- * declaring it in wrangler.
13
- *
14
- * Layout:
15
- * ./core — pure segment/lock/wire logic (unit-testable)
16
- * ./do — the DO transport shell + product extension seams
17
- * ./adapters — turnStore + turnLock seam implementations, broadcast
18
- * helpers, WS upgrade forwarder
19
- * ./memory — in-process harness for tests and keyless local dev
20
- *
21
- * What stays product-side, on purpose: WHICH scope a turn locks on, the
22
- * sandbox/session probes for stale-lock recovery, viewer authorization, and
23
- * any post-turn machinery that defers a lock release (the DO's protected
24
- * seams exist for exactly that).
25
- *
26
- * ── What is still the right answer here, and what is not ─────────────────
27
- *
28
- * A production A/B (4 arms, sandbox.tangle.tools, SDK 0.12.0) showed that a
29
- * browser attached to the sandbox session gateway sees a turn only when the
30
- * turn is driven on the session-MESSAGE lane
31
- * (`box.session(id).sendMessage()` → 297 of 297 frames delivered), never on
32
- * the run/stream lane (`box.streamPrompt()` → 0 of 71, 0 of 527, 0 of 408
33
- * across three session-id strategies). `./core`'s header carries the full
34
- * table.
35
- *
36
- * KEPT — no SDK primitive replaces these:
37
- * • the dual-scope single-flight TURN LOCK (`createDurableTurnLock`,
38
- * `reconcileStaleDurableTurnLock`) — the gateway is a read-only fanout
39
- * and ships no admission control;
40
- * • the per-workspace SIGNALS (`thread.created`, `thread.activity`, plus
41
- * `productSyncEvents`) — the gateway is per-session;
42
- * • the durable TURN-EVENT rows + running-turn index
43
- * (`createDurableObjectTurnEventStore`) that `runDetachedTurn` streams
44
- * into — stream/dispatch detached runs (`dispatchPrompt({ detach: true })`,
45
- * `streamPrompt`) do not reach the gateway on the measured path. Sandbox
46
- * 0.37 `driveTurn` uses the session message lane and is gateway-visible
47
- * by SDK contract. Autonomous stream/dispatch work a browser must tail
48
- * still needs the durable rows.
49
- *
50
- * DEPRECATED — duplicates the SDK:
51
- * • the interactive per-turn REBROADCAST/replay on the thread channel
52
- * (`broadcastTurnStreamEvent` + the segment functions in `./core`).
53
- * Sandbox products: drive on the message lane and attach the tab with
54
- * `box.mintScopedToken({ scope: 'session' })` + `SessionGatewayClient`;
55
- * resume a worker-side read with
56
- * `box.streamPrompt('', { executionId, lastEventId })`, which replays
57
- * strictly after the cursor without re-dispatching.
58
- *
59
- * Nothing is removed: these are published exports and unknown consumers may
60
- * hold them. Removal is a major-version change.
2
+ * Server-only durable turn storage, workspace signals, and single-flight locks.
3
+ * Products bind TurnStreamDO and share TURN_STREAM_AUTH_SECRET with worker adapters.
4
+ * The worker authorizes workspace viewers before forwarding their WebSocket upgrade.
5
+ * Every DO request independently verifies a short-lived token for its own named channel.
6
+ *
7
+ * Interactive turn replay belongs to the sandbox session gateway.
8
+ * The optional turn-event backend is independent of lock and signal coordination.
9
+ * Products own sandbox probes, membership checks, and deferred persistence tasks.
10
+ * See docs/turn-stream-migration.md for the 0.52.0 consumer migration.
61
11
  */
62
12
  export * from './core';
63
13
  export * from './do';
@@ -1,13 +1,35 @@
1
1
  import {
2
2
  reconcileStaleTurnLock
3
3
  } from "../chunk-CCVWR33L.js";
4
+ import {
5
+ base64UrlEncodeText,
6
+ constantTimeEqual,
7
+ hmacSha256Base64Url
8
+ } from "../chunk-S5SRJJQG.js";
4
9
  import {
5
10
  DEFAULT_RUNNING_TURN_LEASE_MS
6
11
  } from "../chunk-HXTJXODG.js";
7
12
 
8
13
  // src/turn-stream/core.ts
9
- function isTerminalRunEvent(type) {
10
- return type === "session.run.completed" || type === "session.run.failed";
14
+ var TURN_STREAM_TOKEN_TTL_MS = 6e4;
15
+ var TURN_STREAM_TOKEN_HEADER = "x-turn-stream-token";
16
+ async function mintTurnStreamToken(channelName, secret, now = Date.now, ttlMs = TURN_STREAM_TOKEN_TTL_MS) {
17
+ if (!secret || secret.length < 32) throw new Error("turn-stream token secret must be at least 32 characters");
18
+ const expiresAt = now() + ttlMs;
19
+ const payload = `v1.${base64UrlEncodeText(channelName)}.${expiresAt.toString(36)}`;
20
+ return `${payload}.${await hmacSha256Base64Url(payload, secret)}`;
21
+ }
22
+ async function verifyTurnStreamToken(channelName, token, secret, now = Date.now) {
23
+ if (!secret || secret.length < 32) return false;
24
+ const parts = token.split(".");
25
+ if (parts.length !== 4 || parts[0] !== "v1") return false;
26
+ const [, name, expires36, mac] = parts;
27
+ if (name !== base64UrlEncodeText(channelName)) return false;
28
+ if (!/^[0-9a-z]+$/.test(expires36)) return false;
29
+ const expiresAt = parseInt(expires36, 36);
30
+ if (!Number.isSafeInteger(expiresAt) || expiresAt <= now()) return false;
31
+ const expected = await hmacSha256Base64Url(`v1.${name}.${expires36}`, secret);
32
+ return constantTimeEqual(mac, expected);
11
33
  }
12
34
  function threadChannelKey(workspaceId, threadId) {
13
35
  return `${workspaceId}:${threadId}`;
@@ -24,40 +46,8 @@ function turnStorageChannelKey(turnId) {
24
46
  function scopeIndexChannelKey(scopeId) {
25
47
  return `scope:${scopeId}`;
26
48
  }
27
- var MAX_SEGMENT_EVENTS = 2e3;
28
49
  var MAX_RECENT_CREATED = 50;
29
50
  var ACTIVITY_TTL_MS = 15 * 60 * 1e3;
30
- function createSegmentStore() {
31
- return { segments: /* @__PURE__ */ new Map(), activeExecutionId: null };
32
- }
33
- function appendSegmentEvent(store, executionId, incoming, maxEvents = MAX_SEGMENT_EVENTS) {
34
- let segment = store.segments.get(executionId);
35
- if (incoming.type === "session.run.started" || !segment) {
36
- if (!segment) {
37
- segment = { events: [], maxSeq: 0, terminal: false };
38
- store.segments.set(executionId, segment);
39
- }
40
- store.activeExecutionId = executionId;
41
- for (const id of store.segments.keys()) {
42
- if (id !== executionId) store.segments.delete(id);
43
- }
44
- }
45
- const seq = ++segment.maxSeq;
46
- const stamped = { ...incoming, seq };
47
- segment.events.push(stamped);
48
- if (segment.events.length > maxEvents) {
49
- segment.events = segment.events.slice(-maxEvents);
50
- }
51
- if (isTerminalRunEvent(incoming.type)) {
52
- segment.terminal = true;
53
- }
54
- return stamped;
55
- }
56
- function replayActiveSegment(store, afterSeq) {
57
- const segment = store.activeExecutionId ? store.segments.get(store.activeExecutionId) : void 0;
58
- if (!segment || segment.terminal) return [];
59
- return segment.events.filter((event) => (event.seq ?? 0) > afterSeq);
60
- }
61
51
  function pruneStaleThreads(active, now, ttlMs) {
62
52
  const removed = [];
63
53
  for (const [threadId, startedAt] of active) {
@@ -143,8 +133,6 @@ var TurnStreamDO = class {
143
133
  state;
144
134
  env;
145
135
  options;
146
- // Thread channel: per-turn segments; only the active one is replayed.
147
- segments = createSegmentStore();
148
136
  // Workspace channel: recent thread.created markers (in-memory, best-effort)
149
137
  // + durable responding set (threadId → startedAt) that survives eviction.
150
138
  recentCreated = [];
@@ -154,9 +142,48 @@ var TurnStreamDO = class {
154
142
  this.env = env;
155
143
  this.options = options;
156
144
  }
145
+ /** The token-verification secret: explicit option first, then the
146
+ * `TURN_STREAM_AUTH_SECRET` env binding. Protected so a product subclass
147
+ * with its own secret store overrides ONE method instead of copying the
148
+ * resolution. */
149
+ resolveAuthSecret() {
150
+ const explicit = this.options.authSecret;
151
+ if (explicit) return explicit;
152
+ const fromEnv = this.env?.TURN_STREAM_AUTH_SECRET;
153
+ return typeof fromEnv === "string" && fromEnv ? fromEnv : void 0;
154
+ }
155
+ /**
156
+ * The single authentication gate for EVERYTHING this DO serves — base
157
+ * endpoints, the WebSocket upgrade, and subclass product routes (they are
158
+ * dispatched from {@link fetch} after this check). A request must present a
159
+ * capability token minted for THIS instance's channel name: cross-channel
160
+ * replay is impossible, an unauthenticated forward gets 401, and a missing
161
+ * secret fails closed with a 500 that names the fix (issue #746).
162
+ */
163
+ async authorizeRequest(request) {
164
+ const name = this.state.id?.name;
165
+ if (typeof name !== "string" || !name) {
166
+ return Response.json(
167
+ { error: "turn-stream DO has no channel name; bind with idFromName so capability tokens can be bound to it" },
168
+ { status: 500 }
169
+ );
170
+ }
171
+ const secret = this.resolveAuthSecret();
172
+ if (!secret || secret.length < 32) {
173
+ return Response.json(
174
+ { error: "turn-stream DO requires authSecret (option or TURN_STREAM_AUTH_SECRET, >= 32 chars); refusing unauthenticated mode" },
175
+ { status: 500 }
176
+ );
177
+ }
178
+ const token = request.headers.get(TURN_STREAM_TOKEN_HEADER) ?? "";
179
+ if (await verifyTurnStreamToken(name, token, secret)) return null;
180
+ return Response.json({ error: "invalid or missing turn-stream capability token" }, { status: 401 });
181
+ }
157
182
  async fetch(request) {
158
183
  const url = new URL(request.url);
159
- if (request.headers.get("Upgrade") === "websocket") {
184
+ const unauthorized = await this.authorizeRequest(request);
185
+ if (unauthorized) return unauthorized;
186
+ if (request.headers.get("Upgrade")?.toLowerCase() === "websocket") {
160
187
  return this.handleWebSocketUpgrade(request, url);
161
188
  }
162
189
  if (request.method === "POST") {
@@ -194,8 +221,7 @@ var TurnStreamDO = class {
194
221
  async handleProductRequest(_request, _url) {
195
222
  return null;
196
223
  }
197
- /** Consulted before any lock release (cooperative, interrupted, or the
198
- * terminal-event auto-release). Return `true` while a product-owned
224
+ /** Consulted before any lock release (cooperative or interrupted). Return `true` while a product-owned
199
225
  * post-turn task for `executionId` must keep the scope serialized (e.g.
200
226
  * file persistence still reading the box) — the release is then parked as
201
227
  * `releasePending` on the lock and completed via
@@ -244,15 +270,13 @@ var TurnStreamDO = class {
244
270
  async webSocketMessage(ws, message) {
245
271
  const meta = ws.deserializeAttachment();
246
272
  if (!meta || meta.synced) return;
247
- let afterSeq = 0;
248
273
  try {
249
274
  const parsed = JSON.parse(typeof message === "string" ? message : "");
250
275
  if (parsed.type !== "sync") return;
251
- afterSeq = typeof parsed.afterSeq === "number" ? parsed.afterSeq : 0;
252
276
  } catch {
253
277
  return;
254
278
  }
255
- if (meta.scope === "workspace") {
279
+ {
256
280
  const active = await this.loadActiveThreads();
257
281
  const removed = pruneStaleThreads(active, Date.now(), this.options.activityTtlMs ?? ACTIVITY_TTL_MS);
258
282
  if (removed.length > 0) await this.persistActiveThreads(active);
@@ -264,10 +288,6 @@ var TurnStreamDO = class {
264
288
  });
265
289
  }
266
290
  for (const event of this.recentCreated) this.trySend(ws, event);
267
- } else {
268
- for (const event of replayActiveSegment(this.segments, afterSeq)) {
269
- this.trySend(ws, event);
270
- }
271
291
  }
272
292
  for (const event of await this.productSyncEvents(meta.scope, { sessionId: meta.sessionId })) {
273
293
  this.trySend(ws, event);
@@ -288,12 +308,11 @@ var TurnStreamDO = class {
288
308
  } catch {
289
309
  }
290
310
  }
291
- // ── broadcast (live fanout + segments + activity) ─────────────────────────
311
+ // ── broadcast (live fanout + activity) ─────────────────────────────────────
292
312
  async handleBroadcast(request) {
293
313
  const incoming = await request.json();
294
314
  const data = incoming.data ?? {};
295
315
  const sessionId = typeof data.sessionId === "string" ? data.sessionId : void 0;
296
- let outgoing = incoming;
297
316
  if (incoming.type === "thread.activity") {
298
317
  const threadId = typeof data.threadId === "string" ? data.threadId : void 0;
299
318
  if (threadId) {
@@ -307,22 +326,8 @@ var TurnStreamDO = class {
307
326
  if (this.recentCreated.length > MAX_RECENT_CREATED) {
308
327
  this.recentCreated = this.recentCreated.slice(-MAX_RECENT_CREATED);
309
328
  }
310
- } else if (typeof data.executionId === "string") {
311
- outgoing = appendSegmentEvent(
312
- this.segments,
313
- data.executionId,
314
- incoming,
315
- this.options.maxSegmentEvents ?? MAX_SEGMENT_EVENTS
316
- );
317
- if (isTerminalRunEvent(incoming.type)) {
318
- if (await this.shouldDeferLockRelease(data.executionId)) {
319
- await this.deferLockRelease({ executionId: data.executionId });
320
- } else {
321
- await this.releaseActiveLock({ executionId: data.executionId });
322
- }
323
- }
324
329
  }
325
- const message = JSON.stringify(outgoing);
330
+ const message = JSON.stringify(incoming);
326
331
  for (const ws of this.state.getWebSockets()) {
327
332
  const meta = ws.deserializeAttachment();
328
333
  if (!meta?.synced) continue;
@@ -502,44 +507,48 @@ var TurnStreamDO = class {
502
507
 
503
508
  // src/turn-stream/adapters.ts
504
509
  var INTERNAL_ORIGIN = "https://turn-stream.internal";
505
- async function postJson(namespace, channelKey, path, body) {
510
+ async function postJson(namespace, channelKey, path, body, auth) {
506
511
  const stub = namespace.get(namespace.idFromName(channelKey));
507
512
  const response = await stub.fetch(`${INTERNAL_ORIGIN}${path}`, {
508
513
  method: "POST",
509
- headers: { "Content-Type": "application/json" },
514
+ headers: {
515
+ "Content-Type": "application/json",
516
+ [TURN_STREAM_TOKEN_HEADER]: await mintTurnStreamToken(channelKey, auth.secret)
517
+ },
510
518
  body: JSON.stringify(body)
511
519
  });
512
520
  return { status: response.status, body: await response.json() };
513
521
  }
514
- async function postJsonOk(namespace, channelKey, path, body) {
515
- const result = await postJson(namespace, channelKey, path, body);
522
+ async function postJsonOk(namespace, channelKey, path, body, auth) {
523
+ const result = await postJson(namespace, channelKey, path, body, auth);
516
524
  if (result.status !== 200) {
517
525
  throw new Error(`turn-stream ${path} failed with status ${result.status}`);
518
526
  }
519
527
  return result.body;
520
528
  }
521
- function createDurableObjectTurnEventStore(namespace) {
529
+ function createDurableObjectTurnEventStore(namespace, auth) {
522
530
  return {
523
531
  async append(turnId, events) {
524
532
  if (!events.length) return;
525
- await postJsonOk(namespace, turnStorageChannelKey(turnId), TURN_STREAM_PATHS.turnEventsAppend, { events });
533
+ await postJsonOk(namespace, turnStorageChannelKey(turnId), TURN_STREAM_PATHS.turnEventsAppend, { events }, auth);
526
534
  },
527
535
  async read(turnId, fromSeq) {
528
536
  const body = await postJsonOk(
529
537
  namespace,
530
538
  turnStorageChannelKey(turnId),
531
539
  TURN_STREAM_PATHS.turnEventsRead,
532
- { fromSeq }
540
+ { fromSeq },
541
+ auth
533
542
  );
534
543
  return body.events;
535
544
  },
536
545
  async setStatus(turnId, status, scopeId) {
537
- await postJsonOk(namespace, turnStorageChannelKey(turnId), TURN_STREAM_PATHS.turnStatusSet, { status });
546
+ await postJsonOk(namespace, turnStorageChannelKey(turnId), TURN_STREAM_PATHS.turnStatusSet, { status }, auth);
538
547
  if (scopeId) {
539
548
  await postJsonOk(namespace, scopeIndexChannelKey(scopeId), TURN_STREAM_PATHS.scopeStatusSet, {
540
549
  turnId,
541
550
  status
542
- });
551
+ }, auth);
543
552
  }
544
553
  },
545
554
  async getStatus(turnId) {
@@ -547,7 +556,8 @@ function createDurableObjectTurnEventStore(namespace) {
547
556
  namespace,
548
557
  turnStorageChannelKey(turnId),
549
558
  TURN_STREAM_PATHS.turnStatusGet,
550
- {}
559
+ {},
560
+ auth
551
561
  );
552
562
  return body.status;
553
563
  },
@@ -556,29 +566,30 @@ function createDurableObjectTurnEventStore(namespace) {
556
566
  namespace,
557
567
  scopeIndexChannelKey(scopeId),
558
568
  TURN_STREAM_PATHS.scopeRunningList,
559
- {}
569
+ {},
570
+ auth
560
571
  );
561
572
  return body.running;
562
573
  }
563
574
  };
564
575
  }
565
- async function acquireDurableTurnLock(namespace, input) {
576
+ async function acquireDurableTurnLock(namespace, input, auth) {
566
577
  const lockId = input.lockId ?? crypto.randomUUID();
567
578
  const key = turnLockChannelKey(input.workspaceId, input.threadId, input.scope);
568
579
  const result = await postJson(namespace, key, TURN_STREAM_PATHS.lockAcquire, {
569
580
  ...input,
570
581
  lockId
571
- });
582
+ }, auth);
572
583
  if (result.status !== 200 && result.status !== 409) {
573
584
  throw new Error(`turn-stream lock acquire failed with status ${result.status}`);
574
585
  }
575
586
  return result.body;
576
587
  }
577
- async function releaseDurableTurnLock(namespace, input) {
588
+ async function releaseDurableTurnLock(namespace, input, auth) {
578
589
  const key = turnLockChannelKey(input.workspaceId, input.threadId, input.scope);
579
- return postJsonOk(namespace, key, TURN_STREAM_PATHS.lockRelease, input);
590
+ return postJsonOk(namespace, key, TURN_STREAM_PATHS.lockRelease, input, auth);
580
591
  }
581
- async function releaseInterruptedDurableTurnLock(namespace, input) {
592
+ async function releaseInterruptedDurableTurnLock(namespace, input, auth) {
582
593
  const scopes = input.scope ? [input.scope] : ["workspace", "thread"];
583
594
  for (const scope of scopes) {
584
595
  const key = turnLockChannelKey(input.workspaceId, input.threadId, scope);
@@ -586,13 +597,13 @@ async function releaseInterruptedDurableTurnLock(namespace, input) {
586
597
  threadId: input.threadId,
587
598
  interruptedAt: input.interruptedAt,
588
599
  ...input.turnId ? { turnId: input.turnId } : {}
589
- });
600
+ }, auth);
590
601
  if (result.released) return true;
591
602
  }
592
603
  return false;
593
604
  }
594
605
  async function reconcileStaleDurableTurnLock(options) {
595
- const { namespace, workspaceId, threadId, active, ...policy } = options;
606
+ const { namespace, auth, workspaceId, threadId, active, ...policy } = options;
596
607
  return reconcileStaleTurnLock({
597
608
  ...policy,
598
609
  lockStartedAt: active.startedAt,
@@ -602,7 +613,7 @@ async function reconcileStaleDurableTurnLock(options) {
602
613
  scope: active.scope,
603
614
  interruptedAt: fence.observedAt,
604
615
  ...active.turnId ? { turnId: active.turnId } : {}
605
- })
616
+ }, auth)
606
617
  });
607
618
  }
608
619
  function defaultRefusalResponse(active, diagnostics) {
@@ -638,13 +649,13 @@ function createDurableTurnLock(options) {
638
649
  executionId,
639
650
  ...turnId ? { turnId } : {}
640
651
  };
641
- let acquired = await acquireDurableTurnLock(options.namespace, input);
652
+ let acquired = await acquireDurableTurnLock(options.namespace, input, options.auth);
642
653
  let diagnostics;
643
654
  if (!acquired.acquired && options.reconcile) {
644
655
  const reconciled = await options.reconcile(args, acquired.active);
645
656
  diagnostics = reconciled.diagnostics;
646
657
  if (reconciled.released) {
647
- acquired = await acquireDurableTurnLock(options.namespace, input);
658
+ acquired = await acquireDurableTurnLock(options.namespace, input, options.auth);
648
659
  }
649
660
  }
650
661
  if (!acquired.acquired) {
@@ -664,63 +675,54 @@ function createDurableTurnLock(options) {
664
675
  },
665
676
  async release(handle) {
666
677
  if (!handle) return;
667
- await releaseDurableTurnLock(options.namespace, handle);
678
+ await releaseDurableTurnLock(options.namespace, handle, options.auth);
668
679
  }
669
680
  };
670
681
  }
671
- async function broadcastTurnStreamEvent(namespace, input) {
672
- try {
673
- await postJson(namespace, threadChannelKey(input.workspaceId, input.threadId), TURN_STREAM_PATHS.broadcast, {
674
- type: input.event.type,
675
- timestamp: Date.now(),
676
- data: {
677
- ...input.event.data ?? {},
678
- workspaceId: input.workspaceId,
679
- threadId: input.threadId,
680
- sessionId: input.threadId,
681
- executionId: input.executionId
682
- }
683
- });
684
- } catch {
685
- }
686
- }
687
- async function broadcastWorkspaceActivity(namespace, workspaceId, threadId, phase) {
682
+ async function broadcastWorkspaceActivity(namespace, workspaceId, threadId, phase, auth) {
688
683
  try {
689
684
  await postJson(namespace, workspaceChannelKey(workspaceId), TURN_STREAM_PATHS.broadcast, {
690
685
  type: "thread.activity",
691
686
  timestamp: Date.now(),
692
687
  data: { threadId, phase, workspaceId, sessionId: workspaceId }
693
- });
688
+ }, auth);
694
689
  } catch {
695
690
  }
696
691
  }
697
- async function broadcastThreadCreated(namespace, workspaceId, thread) {
692
+ async function broadcastThreadCreated(namespace, workspaceId, thread, auth) {
698
693
  try {
699
694
  await postJson(namespace, workspaceChannelKey(workspaceId), TURN_STREAM_PATHS.broadcast, {
700
695
  type: "thread.created",
701
696
  timestamp: Date.now(),
702
697
  data: { threadId: thread.threadId, title: thread.title, workspaceId, sessionId: workspaceId }
703
- });
698
+ }, auth);
704
699
  } catch {
705
700
  }
706
701
  }
707
702
  function createTurnStreamUpgradeHandler(options) {
708
703
  const path = options.path ?? "/api/session-stream";
704
+ if (!options.authSecret || options.authSecret.length < 32) {
705
+ throw new Error("createTurnStreamUpgradeHandler requires authSecret (>= 32 chars) \u2014 the DO fails closed without tokens");
706
+ }
709
707
  return async (request) => {
710
708
  const url = new URL(request.url);
711
- if (url.pathname !== path || request.headers.get("Upgrade") !== "websocket") return null;
709
+ if (url.pathname !== path || request.headers.get("Upgrade")?.toLowerCase() !== "websocket") return null;
710
+ if (url.searchParams.has("threadId")) {
711
+ return new Response("Thread replay uses the sandbox session gateway or chat replay route", { status: 400 });
712
+ }
712
713
  const workspaceId = url.searchParams.get("workspaceId");
713
- const threadId = url.searchParams.get("threadId");
714
714
  if (!workspaceId) return new Response("Missing workspaceId", { status: 400 });
715
- const auth = await options.authorize(request, { workspaceId, threadId });
715
+ const auth = await options.authorize(request, { workspaceId });
716
716
  if (!auth.ok) return auth.response;
717
- const key = threadId ? threadChannelKey(workspaceId, threadId) : workspaceChannelKey(workspaceId);
718
- const sessionId = threadId ?? workspaceId;
717
+ const key = workspaceChannelKey(workspaceId);
719
718
  const stub = options.namespace.get(options.namespace.idFromName(key));
720
719
  const forwardUrl = new URL(request.url);
721
- forwardUrl.searchParams.set("sessionId", sessionId);
722
- forwardUrl.searchParams.set("scope", threadId ? "thread" : "workspace");
723
- return stub.fetch(new Request(forwardUrl, request));
720
+ forwardUrl.searchParams.set("sessionId", workspaceId);
721
+ forwardUrl.searchParams.set("scope", "workspace");
722
+ forwardUrl.searchParams.delete("token");
723
+ const headers = new Headers(request.headers);
724
+ headers.set(TURN_STREAM_TOKEN_HEADER, await mintTurnStreamToken(key, options.authSecret));
725
+ return stub.fetch(new Request(new Request(forwardUrl, request), { headers }));
724
726
  };
725
727
  }
726
728
 
@@ -743,7 +745,10 @@ function createMemoryStorage() {
743
745
  }
744
746
  };
745
747
  }
746
- function createMemoryTurnStreamHarness(createInstance = (state) => new TurnStreamDO(state), _options = {}) {
748
+ var MEMORY_TURN_STREAM_AUTH_SECRET = "test-turn-stream-harness-secret-0123456789ab";
749
+ function createMemoryTurnStreamHarness(createInstance = (state, secret) => new TurnStreamDO(state, void 0, { authSecret: secret }), options = {}) {
750
+ const authSecret = options.authSecret ?? MEMORY_TURN_STREAM_AUTH_SECRET;
751
+ const createInst = (state) => createInstance(state, authSecret);
747
752
  const instances = /* @__PURE__ */ new Map();
748
753
  function ensure(name) {
749
754
  let entry = instances.get(name);
@@ -752,9 +757,10 @@ function createMemoryTurnStreamHarness(createInstance = (state) => new TurnStrea
752
757
  const state = {
753
758
  storage: createMemoryStorage(),
754
759
  acceptWebSocket: (ws) => sockets.push(ws),
755
- getWebSockets: () => sockets.filter((ws) => !ws.closed)
760
+ getWebSockets: () => sockets.filter((ws) => !ws.closed),
761
+ id: { name }
756
762
  };
757
- entry = { instance: createInstance(state), sockets };
763
+ entry = { instance: createInst(state), sockets };
758
764
  instances.set(name, entry);
759
765
  }
760
766
  return entry;
@@ -811,36 +817,35 @@ function createMemoryTurnStreamHarness(createInstance = (state) => new TurnStrea
811
817
  export {
812
818
  ACTIVITY_TTL_MS,
813
819
  MAX_RECENT_CREATED,
814
- MAX_SEGMENT_EVENTS,
820
+ MEMORY_TURN_STREAM_AUTH_SECRET,
815
821
  TURN_LOCK_TTL_MS,
816
822
  TURN_STREAM_PATHS,
817
823
  TURN_STREAM_STORAGE_KEYS,
824
+ TURN_STREAM_TOKEN_HEADER,
825
+ TURN_STREAM_TOKEN_TTL_MS,
818
826
  TurnStreamDO,
819
827
  acquireDurableTurnLock,
820
828
  activeTurnLock,
821
- appendSegmentEvent,
822
829
  broadcastThreadCreated,
823
- broadcastTurnStreamEvent,
824
830
  broadcastWorkspaceActivity,
825
831
  createDurableObjectTurnEventStore,
826
832
  createDurableTurnLock,
827
833
  createMemoryTurnStreamHarness,
828
- createSegmentStore,
829
834
  createTurnLock,
830
835
  createTurnStreamUpgradeHandler,
831
836
  interruptedReleaseApplies,
832
- isTerminalRunEvent,
837
+ mintTurnStreamToken,
833
838
  pruneStaleThreads,
834
839
  reconcileStaleDurableTurnLock,
835
840
  releaseDurableTurnLock,
836
841
  releaseInterruptedDurableTurnLock,
837
- replayActiveSegment,
838
842
  scopeIndexChannelKey,
839
843
  threadChannelKey,
840
844
  turnEventStorageKey,
841
845
  turnLockChannelKey,
842
846
  turnLockMatchesRelease,
843
847
  turnStorageChannelKey,
848
+ verifyTurnStreamToken,
844
849
  workspaceChannelKey
845
850
  };
846
851
  //# sourceMappingURL=index.js.map