my-durable 0.0.60 → 0.0.62

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.
@@ -27,6 +27,14 @@ import {
27
27
  } from "../../../../dpi-sdk/src/protocol/limits.js";
28
28
  import { ByteBudget, ChunkReassembler } from "../../../../dpi-sdk/src/node/chunk.js";
29
29
  import type { DeviceTransport, TransportRequest, TransportResponse } from "./transport.js";
30
+
31
+ /** Device frames are untrusted at the ADMIN origin: printable ASCII only, bounded length
32
+ * (defense in depth — the device already sanitizes before putting it on the wire). */
33
+ const safeHeaderValue = (value: unknown): string | undefined => {
34
+ if (typeof value !== "string") return undefined;
35
+ const clean = value.replace(/[^\x20-\x7E]/g, "").slice(0, 200).trim();
36
+ return clean.length > 0 ? clean : undefined;
37
+ };
30
38
  import type { TunnelConnection, TunnelServer } from "./tunnel.js";
31
39
  import type { Audit } from "./audit.js";
32
40
 
@@ -179,6 +187,10 @@ export class TunnelDispatcher {
179
187
  status: frame.status as number,
180
188
  contentType: frame.contentType as string | undefined,
181
189
  body: frame.body,
190
+ ...(frame.bodyEncoding === "base64" ? { bodyEncoding: "base64" as const } : {}),
191
+ ...(frame.bodyEncoding === "base64"
192
+ ? { contentDisposition: safeHeaderValue(frame.contentDisposition) }
193
+ : {}),
182
194
  });
183
195
  return;
184
196
  }
@@ -220,7 +232,13 @@ export class TunnelDispatcher {
220
232
  // inside chunk data with no schema. A missing or non-numeric status is the device
221
233
  // breaking contract: answer a bad gateway, never a silently defaulted 200.
222
234
  const env = out.value as
223
- | { status?: unknown; contentType?: unknown; body?: unknown }
235
+ | {
236
+ status?: unknown;
237
+ contentType?: unknown;
238
+ body?: unknown;
239
+ bodyEncoding?: unknown;
240
+ contentDisposition?: unknown;
241
+ }
224
242
  | undefined;
225
243
  if (typeof env?.status !== "number" || !Number.isFinite(env.status)) {
226
244
  p?.resolve({
@@ -235,6 +253,10 @@ export class TunnelDispatcher {
235
253
  status: env.status,
236
254
  contentType: typeof env.contentType === "string" ? env.contentType : undefined,
237
255
  body: env.body,
256
+ ...(env.bodyEncoding === "base64" ? { bodyEncoding: "base64" as const } : {}),
257
+ ...(env.bodyEncoding === "base64"
258
+ ? { contentDisposition: safeHeaderValue(env.contentDisposition) }
259
+ : {}),
238
260
  rawBytes: out.rawBytes,
239
261
  });
240
262
  }
@@ -52,6 +52,15 @@ const enc = encodeURIComponent;
52
52
  const newId = (): string =>
53
53
  globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`;
54
54
 
55
+ /** "My session #1" → "my-session-1" — mirrors the device's download slug (zip.ts). */
56
+ const slugName = (input: string): string =>
57
+ input
58
+ .normalize("NFKD")
59
+ .replace(/[^\w.-]+/g, "-")
60
+ .replace(/^-+|-+$/g, "")
61
+ .slice(0, 60)
62
+ .toLowerCase() || "session";
63
+
55
64
  /**
56
65
  * Typed client for one dpi-backend. Works in browsers and Node (fetch + streams).
57
66
  * `token` is optional: the playground hub injects it, so browsers never hold one.
@@ -113,6 +122,20 @@ export type GitOpName =
113
122
  | "pr-checks"
114
123
  | "pr-comment";
115
124
 
125
+ /** One zipped session bundle, downloaded as raw bytes (R8 binary contract):
126
+ * the device streams plain `application/zip` bytes, so there is no base64
127
+ * hop. Hand `bytes` straight to `new Blob(...)` in the browser or to
128
+ * `fs.writeFile` in Node. */
129
+ export interface SessionExport {
130
+ /** The device's download name (`${slug}.bundle.zip`), from Content-Disposition
131
+ * — a slug of the session ref when the peer sends no usable header. */
132
+ filename: string;
133
+ /** The response's media type; `application/zip` from the device route. */
134
+ mime: string;
135
+ /** The zip payload, byte-for-byte as the device streamed it. */
136
+ bytes: Uint8Array;
137
+ }
138
+
116
139
  /** Everything a git op may return; most carry only text. */
117
140
  export interface GitOpResult {
118
141
  text: string;
@@ -358,12 +381,56 @@ export class DpiClient {
358
381
  return this.request<GitOpResult>("POST", "/v1/git", { path, op, ...opts });
359
382
  }
360
383
  /** Paths this session's agents wrote/edited — the session-changelist. */
361
- /** One zipped bundle of a session (manifest + record + agent transcripts/configs). */
362
- exportSession(sessionId: string) {
363
- return this.request<{ filename: string; mime: string; bytes: number; base64: string }>(
364
- "GET",
365
- `/v1/sessions/${enc(sessionId)}/export`,
366
- );
384
+ /** One zipped bundle of a session (manifest + record + agent transcripts/configs),
385
+ * downloaded as RAW zip bytes since R8 — the route streams `application/zip` with
386
+ * Content-Length + Content-Disposition instead of the old base64 JSON envelope.
387
+ * Returns { filename, mime, bytes }: `filename` parsed from Content-Disposition
388
+ * (slug-of-ref fallback), `mime` from Content-Type, `bytes` the zip payload —
389
+ * Blob-able in the browser, fs.writeFile-able in Node. Refusal faults keep their
390
+ * JSON error bodies and throw the usual DpiError. Bundles can be large — pass a
391
+ * longer timeoutMs on slow links (default 60s). */
392
+ async exportSession(sessionId: string, options: RequestOptions = {}): Promise<SessionExport> {
393
+ const timeout = AbortSignal.timeout(options.timeoutMs ?? 60_000);
394
+ const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;
395
+ let response: Response;
396
+ try {
397
+ response = await fetch(this.baseUrl + `/v1/sessions/${enc(sessionId)}/export`, {
398
+ headers: this.headers(false),
399
+ signal,
400
+ });
401
+ } catch (cause) {
402
+ if (options.signal?.aborted) throw cause;
403
+ throw new DpiError("offline", `Cannot reach ${this.baseUrl}`, 0, { cause });
404
+ }
405
+ if (!response.ok) {
406
+ // Refusals keep speaking JSON faults even on this binary route.
407
+ const text = await response.text().catch(() => "");
408
+ let data: { error?: { code?: ErrorCode; message?: string } } | undefined;
409
+ try {
410
+ data = text ? (JSON.parse(text) as typeof data) : undefined;
411
+ } catch {
412
+ data = undefined;
413
+ }
414
+ const code: ErrorCode =
415
+ data?.error?.code ??
416
+ (response.status === 401 ? "unauthorized" : response.status === 404 ? "not_found" : "internal");
417
+ throw new DpiError(
418
+ code,
419
+ data?.error?.message ?? `${response.status} ${response.statusText}`,
420
+ response.status,
421
+ );
422
+ }
423
+ const bytes = new Uint8Array(await response.arrayBuffer());
424
+ // `filename="quoted"` (the device's form) or a bare token, per RFC 6266.
425
+ const disposition = response.headers.get("content-disposition") ?? "";
426
+ const quoted = /filename="((?:[^"\\]|\\.)*)"/i.exec(disposition)?.[1];
427
+ const bare = /filename=([^;\s]+)/i.exec(disposition)?.[1];
428
+ const named = quoted !== undefined ? quoted.replace(/\\(.)/g, "$1") : bare;
429
+ return {
430
+ filename: named || `${slugName(sessionId)}.bundle.zip`,
431
+ mime: response.headers.get("content-type") ?? "application/zip",
432
+ bytes,
433
+ };
367
434
  }
368
435
  sessionGitFiles(sessionId: string) {
369
436
  return this.request<{ files: string[] }>("GET", `/v1/sessions/${enc(sessionId)}/git-files`);
@@ -222,6 +222,10 @@ export const TunnelFrame = Type.Union([
222
222
  status: Type.Integer({ minimum: 100, maximum: 599 }),
223
223
  contentType: Type.Optional(Type.String({ maxLength: 256 })),
224
224
  body: Type.Optional(Type.Unknown()),
225
+ // R8 binary passthrough: non-textual device responses carry base64 bytes plus a
226
+ // sanitized download filename. Absent on the legacy textual envelope.
227
+ bodyEncoding: Type.Optional(Type.Union([Type.Literal("base64")])),
228
+ contentDisposition: Type.Optional(Type.String({ maxLength: 200 })),
225
229
  },
226
230
  Strict,
227
231
  ),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "my-durable",
3
- "version": "0.0.60",
3
+ "version": "0.0.62",
4
4
  "description": "Durable Pi — the durable agent network: hub web UI, device backend daemon, TUI admin and the shared SDK, packaged as one runnable monorepo install",
5
5
  "license": "MIT",
6
6
  "repository": {