@jini-ai/http-kit 0.4.1 → 0.4.2

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.
Files changed (56) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/package.json +7 -7
  3. package/dist/active-context.d.ts +0 -99
  4. package/dist/active-context.js +0 -77
  5. package/dist/agents.d.ts +0 -64
  6. package/dist/agents.js +0 -23
  7. package/dist/attachments.d.ts +0 -534
  8. package/dist/attachments.js +0 -1032
  9. package/dist/cancel-owned-runs.d.ts +0 -44
  10. package/dist/cancel-owned-runs.js +0 -35
  11. package/dist/component-catalog.d.ts +0 -74
  12. package/dist/component-catalog.js +0 -74
  13. package/dist/connectors.d.ts +0 -165
  14. package/dist/connectors.js +0 -474
  15. package/dist/daemon-status.d.ts +0 -72
  16. package/dist/daemon-status.js +0 -60
  17. package/dist/db-ops.d.ts +0 -116
  18. package/dist/db-ops.js +0 -191
  19. package/dist/delegated-tools.d.ts +0 -146
  20. package/dist/delegated-tools.js +0 -286
  21. package/dist/frontend-control.d.ts +0 -131
  22. package/dist/frontend-control.js +0 -77
  23. package/dist/frontend-sessions.d.ts +0 -100
  24. package/dist/frontend-sessions.js +0 -180
  25. package/dist/health.d.ts +0 -91
  26. package/dist/health.js +0 -53
  27. package/dist/host-tools.d.ts +0 -174
  28. package/dist/host-tools.js +0 -338
  29. package/dist/media.d.ts +0 -131
  30. package/dist/media.js +0 -352
  31. package/dist/memory.d.ts +0 -230
  32. package/dist/memory.js +0 -331
  33. package/dist/model-proxy.d.ts +0 -45
  34. package/dist/model-proxy.js +0 -619
  35. package/dist/origin-validation.d.ts +0 -64
  36. package/dist/origin-validation.js +0 -226
  37. package/dist/read-only-tools.d.ts +0 -67
  38. package/dist/read-only-tools.js +0 -59
  39. package/dist/remote-run-events.d.ts +0 -66
  40. package/dist/remote-run-events.js +0 -230
  41. package/dist/research.d.ts +0 -42
  42. package/dist/research.js +0 -316
  43. package/dist/route-manifest.d.ts +0 -31
  44. package/dist/route-manifest.js +0 -103
  45. package/dist/routines.d.ts +0 -114
  46. package/dist/routines.js +0 -320
  47. package/dist/runs.d.ts +0 -79
  48. package/dist/runs.js +0 -232
  49. package/dist/terminals.d.ts +0 -125
  50. package/dist/terminals.js +0 -349
  51. package/dist/tool-catalog.d.ts +0 -68
  52. package/dist/tool-catalog.js +0 -68
  53. package/dist/workspace-root.d.ts +0 -69
  54. package/dist/workspace-root.js +0 -63
  55. package/dist/xai.d.ts +0 -86
  56. package/dist/xai.js +0 -668
@@ -1,1032 +0,0 @@
1
- /**
2
- * @module attachments
3
- *
4
- * `POST /api/attachments`, `DELETE /api/attachments` — an HTTP route pack for user file/image
5
- * uploads staged for one agent run, over a narrow, transport-owned `AttachmentStore` port plus a
6
- * batteries-included disk implementation (`createDiskAttachmentStore`).
7
- *
8
- * **The capability this closes.** A chat composer that accepts drag-and-drop needs somewhere to put
9
- * the bytes, a way to hand the agent a path it is actually allowed to read, and a guarantee that
10
- * those bytes disappear when the run ends. That is three separate concerns (an upload endpoint, a
11
- * trusted-metadata registry, and a run-scoped lifetime) which every host would otherwise hand-roll.
12
- * This module owns all three; `@jini-ai/chat-react`'s `createDaemonAttachmentUploader` is the
13
- * matching client half.
14
- *
15
- * **Trust model.** A renderer supplies bytes, a filename, and a batch id. None of that is trusted:
16
- * - the filename is reduced to a basename over a conservative character allowlist
17
- * (`sanitizeAttachmentName`) and is only ever used as *display* text plus a short extension
18
- * suffix — never as the stored filename, which is a fresh `randomUUID()`;
19
- * - the `kind` (`'image' | 'file'`) is sniffed from the leading bytes (`detectAttachmentKind`),
20
- * never taken from a renderer-controlled MIME type or file extension;
21
- * - the byte count is measured while streaming, never read from a client-supplied length;
22
- * - the returned `path` is an opaque `attachment:<uuid>` capability id, not a filesystem path, so a
23
- * renderer never learns where the upload root is and cannot name a file it did not upload.
24
- * `claim()` is what exchanges those ids for real paths, server-side.
25
- *
26
- * **What `claim()` guarantees.** Exactly once per registered attachment, and only if the file is
27
- * still the same file: `lstat` must report a regular non-symlink whose `dev`/`ino`/`size` match
28
- * what was recorded at registration, and `realpath` must equal the recorded path (so neither the
29
- * file nor any parent directory was swapped for a symlink between upload and run start). Every
30
- * claimed attachment must belong to one batch, so the single `batchDirectory` a host grants the
31
- * agent read access to cannot be widened by mixing batches.
32
- *
33
- * **Ownership is opt-in and host-attached, not self-asserted.** `register()`'s optional `ownerId`
34
- * (and `listPendingForOwner`, the discovery method it enables) is never read from anything a
35
- * renderer sends — a host wires `AttachmentsHttpDeps.resolveOwnerId` to pull it from a channel IT
36
- * already trusts (its own session-verified principal header, say), never from `req` unauthenticated.
37
- * A store with no `resolveOwnerId` wired registers every attachment ownerless, and
38
- * `listPendingForOwner` never returns an ownerless record for any caller — see that method's own doc
39
- * for why an absent `ownerId` must never become a wildcard match.
40
- *
41
- * **Storage lifetime is daemon-lifetime by default, and opt-in restart-surviving.** With
42
- * `retainAcrossRestarts` left off (the default, and this pack's only behavior before that option
43
- * existed), `createDiskAttachmentStore` empties its upload directory on construction: files left
44
- * behind by an interrupted previous process cannot be authenticated against an in-memory registry
45
- * that no longer exists, so they are removed rather than adopted. Unclaimed uploads also expire by
46
- * TTL (`pruneExpired`), and a run's claimed files are deleted by `cleanupRun`.
47
- *
48
- * That default is wrong for any host whose process restarts while a person is still using the
49
- * composer. A file-watching dev server restarting the daemon on an unrelated source edit is not a
50
- * crash, but the construction wipe cannot tell the two apart, so it destroys uploads the user is
51
- * about to send — real data loss, not a tidy-up. `retainAcrossRestarts: true` replaces "wipe
52
- * everything, always" with "adopt exactly what can still be authenticated": see
53
- * {@link prepareAttachmentStorage} for the whole mechanism and {@link loadPersistedAttachments} for
54
- * why an adopted record is no less trusted than one this process registered itself.
55
- *
56
- * **This pack does not auto-wire itself into a run's lifecycle**, because no generic hook for that
57
- * exists — the same deliberate choice `@jini-ai/daemon`'s `createRunScopedContextStore` makes. A
58
- * host claims in its own `onRunStarted` and cleans up in a `finally`, roughly:
59
- *
60
- * ```ts
61
- * const store = await createDiskAttachmentStore({ uploadDirectory });
62
- * // ... httpExtensions: [(app, { adapter }) => registerAttachmentRoutes(app, { store }, adapter)]
63
- * onRunStarted: (context) => {
64
- * void (async () => {
65
- * try {
66
- * const claimed = await store.claim(attachmentRefsFrom(context.request), context.run.id);
67
- * await executor.run({
68
- * runId: context.run.id,
69
- * // ... prompt, cwd, agentId
70
- * ...(claimed.batchDirectory === undefined ? {} : {
71
- * imagePaths: claimed.attachments.filter((a) => a.kind === 'image').map((a) => a.path),
72
- * extraAllowedDirs: [claimed.batchDirectory],
73
- * uploadRoot: claimed.batchDirectory,
74
- * }),
75
- * });
76
- * } finally {
77
- * await store.cleanupRun(context.run.id);
78
- * }
79
- * })();
80
- * }
81
- * ```
82
- *
83
- * `imagePaths`/`extraAllowedDirs`/`uploadRoot` are pre-existing `AgentExecutor.run()` options; this
84
- * module only produces real values for them.
85
- *
86
- * **Body-parser ordering (`POST` reads the raw request stream).** The upload route streams
87
- * `request` straight to disk, so any body-parsing middleware that has already consumed the stream
88
- * leaves nothing to write. The classic way to hit this is a JSON body parser mounted app-wide: a
89
- * user drops a `.json` file, the browser sets `content-type: application/json`, and
90
- * `express.json()` eats the body — which without a guard shows up as the deeply unhelpful
91
- * "attachment is empty". `registerAttachmentRoutes` detects an already-consumed stream up front and
92
- * reports it as a host misconfiguration (`'attachment-body-consumed'`) instead of failing silently.
93
- * Mount this pack before any global body parser, or scope the parser so it skips this path.
94
- *
95
- * **SEC-005 redaction**: a store failure can carry filesystem paths a caller must not see, so
96
- * anything that is not an explicitly-classified `AttachmentRejectedError` becomes a
97
- * correlation-id-bearing generic `INTERNAL_ERROR`, with the real error reaching a host-owned sink —
98
- * the same `reportInternalError` shape `media.ts`/`delegated-tools.ts` use.
99
- */
100
- import { chmod, lstat, mkdir, open, readFile, readdir, realpath, rm, rmdir, writeFile } from 'node:fs/promises';
101
- import { randomUUID } from 'node:crypto';
102
- import { basename, dirname, extname, resolve } from 'node:path';
103
- import { createApiError } from '@jini-ai/protocol';
104
- import { guardSameOrigin } from './origin.js';
105
- import { sendApiError, sendJson } from './response.js';
106
- /**
107
- * A refusal this module classified itself, as opposed to an unexpected filesystem/programming
108
- * error. The route pack turns the `reason` into a status code and lets the `message` through to the
109
- * caller; anything that is *not* one of these is redacted to a generic `INTERNAL_ERROR`.
110
- */
111
- export class AttachmentRejectedError extends Error {
112
- reason;
113
- constructor(reason, message) {
114
- super(message);
115
- this.name = 'AttachmentRejectedError';
116
- this.reason = reason;
117
- }
118
- }
119
- /** The subset of `AttachmentRejectionReason` a caller is allowed to see a real message for. */
120
- const REJECTION_STATUS = {
121
- 'invalid-batch': 400,
122
- 'attachment-too-large': 413,
123
- 'batch-count-exceeded': 413,
124
- 'batch-too-large': 413,
125
- 'storage-full': 413,
126
- 'empty-attachment': 400,
127
- 'too-many-concurrent-uploads': 429,
128
- 'invalid-cleanup-request': 400,
129
- // The remaining reasons describe a broken or hostile server-side state. They are never given a
130
- // real message over HTTP (see `respondToUploadFailure`); the entries exist so a host catching a
131
- // rejection from `claim()` outside HTTP can still classify it.
132
- 'attachment-body-consumed': 500,
133
- 'attachment-integrity': 500,
134
- 'too-many-attachments': 400,
135
- 'duplicate-attachment': 400,
136
- 'attachment-unknown-or-claimed': 400,
137
- 'mixed-batch': 400,
138
- };
139
- /** `ApiError` code per refusal, so `sendApiError` produces the standard envelope. */
140
- function apiErrorForRejection(error) {
141
- const status = REJECTION_STATUS[error.reason];
142
- if (status === 413)
143
- return createApiError('PAYLOAD_TOO_LARGE', error.message);
144
- if (status === 429)
145
- return createApiError('RATE_LIMITED', error.message);
146
- return createApiError('BAD_REQUEST', error.message);
147
- }
148
- /**
149
- * Accepted batch id shape. Deliberately narrow — long enough for a UUID, and admitting no `.`,
150
- * `/`, or `\`, which is what makes `resolve(uploadRoot, batchId)` provably a single
151
- * non-traversing path segment.
152
- */
153
- const BATCH_ID_PATTERN = /^[a-zA-Z0-9-]{8,80}$/u;
154
- /**
155
- * `true` when `body`'s bytes 4-7 spell `ftyp` — the ISO-BMFF box tag AVIF, HEIC, and MP4 all
156
- * share. This says only "some member of the ISO-BMFF family", never "MP4" or "AVIF" on its own:
157
- * mirrors `@jini-ai/cms`'s `content-type-sniffer.ts` `isIsoBmffFtyp`, which documents the same
158
- * fact for the media route's own sniffer. `detectAttachmentKind` never returns `'image'` for this
159
- * tag alone (see that function's doc) — doing so is exactly the 2026-09-06 regression that made an
160
- * AVIF render as an unplayable `<video>` when the *media* sniffer briefly had the same bug.
161
- */
162
- function hasIsoBmffFtypTag(body) {
163
- return body.length >= 8 && new TextDecoder().decode(body.slice(4, 8)) === 'ftyp';
164
- }
165
- /** ISO-BMFF brands that identify AVIF: a still image (`avif`) or an image sequence (`avis`). Kept
166
- * identical to `content-type-sniffer.ts`'s `AVIF_BRANDS` so the two sniffers can never disagree on
167
- * which brands mean AVIF. */
168
- const AVIF_FTYP_BRANDS = ['avif', 'avis'];
169
- const FTYP_MAJOR_BRAND_OFFSET = 8;
170
- /** Compatible brands follow the major brand (offset 8) and 4-byte minor version (offset 12). */
171
- const FTYP_COMPATIBLE_BRANDS_OFFSET = 16;
172
- /** Bound on the compatible-brand list scan — real `ftyp` boxes carry a handful, never dozens. */
173
- const MAX_SCANNED_COMPATIBLE_BRANDS = 16;
174
- function hasAvifBrandAt(body, offset) {
175
- return body.length >= offset + 4
176
- && AVIF_FTYP_BRANDS.some((brand) => new TextDecoder().decode(body.slice(offset, offset + 4)) === brand);
177
- }
178
- /** The `ftyp` box's declared end offset (big-endian size at bytes 0-3), clamped to the bytes
179
- * actually present so a truncated or size-inflating file can never push the brand scan past the
180
- * captured signature window. */
181
- function ftypBoxEnd(body) {
182
- if (body.length < FTYP_MAJOR_BRAND_OFFSET)
183
- return 0;
184
- const declared = ((body[0] << 24) | (body[1] << 16) | (body[2] << 8) | body[3]) >>> 0;
185
- return Math.min(declared, body.length);
186
- }
187
- /**
188
- * `true` when `body` opens with an ISO-BMFF `ftyp` box whose major brand or compatible-brand list
189
- * names AVIF. This is a line-for-line mirror of `@jini-ai/cms`'s `content-type-sniffer.ts`
190
- * `isAvif` (no shared dependency exists between `@jini-ai/http-kit` and `@jini-ai/cms` today — see
191
- * this module's handoff notes on whether extracting one is worth it): the major brand alone is not
192
- * sufficient, because a great many real AVIF files declare the generic `mif1` (HEIF image) major
193
- * brand and name `avif` only in the compatible-brand list, so both are checked. HEIC declares
194
- * neither and is therefore never matched here — deliberate; nothing downstream of this attachment
195
- * store has confirmed it can render a HEIC as an `<img>`, so labelling one `'image'` would risk the
196
- * same "sniffed as a type the surface cannot actually display" failure this whole fix addresses.
197
- *
198
- * Must run before any generic `ftyp` check: {@link hasIsoBmffFtypTag} alone cannot tell AVIF, HEIC,
199
- * and MP4 apart, so a brand-blind caller would misclassify every ISO-BMFF file it sees as one type.
200
- */
201
- export function hasAvifSignature(body) {
202
- if (!hasIsoBmffFtypTag(body))
203
- return false;
204
- if (hasAvifBrandAt(body, FTYP_MAJOR_BRAND_OFFSET))
205
- return true;
206
- const boxEnd = ftypBoxEnd(body);
207
- for (let index = 0; index < MAX_SCANNED_COMPATIBLE_BRANDS; index++) {
208
- const offset = FTYP_COMPATIBLE_BRANDS_OFFSET + index * 4;
209
- if (offset + 4 > boxEnd)
210
- return false;
211
- if (hasAvifBrandAt(body, offset))
212
- return true;
213
- }
214
- return false;
215
- }
216
- /**
217
- * Bytes of leading signature `detectAttachmentKind` needs. WEBP's marker ends at byte 12; AVIF
218
- * needs more — {@link hasAvifSignature}'s compatible-brand scan can read as far as
219
- * `FTYP_COMPATIBLE_BRANDS_OFFSET + MAX_SCANNED_COMPATIBLE_BRANDS * 4` (a great many real AVIF
220
- * files declare the generic `mif1` major brand and name `avif` only in the compatible-brand list —
221
- * see that function's doc), so this is sized to that worst case rather than to the smallest format.
222
- */
223
- const SIGNATURE_BYTES = FTYP_COMPATIBLE_BRANDS_OFFSET + MAX_SCANNED_COMPATIBLE_BRANDS * 4;
224
- /**
225
- * `true` when the file on disk is still the same file registration accepted.
226
- *
227
- * Every condition is a distinct real attack: a regular file swapped for a symlink or directory, a
228
- * parent directory swapped for a symlink pointing elsewhere, the file replaced by a different file
229
- * at the same path (new inode), the same inode truncated or appended to (new size), or the path
230
- * now resolving onto a different device.
231
- *
232
- * Pure and exported on purpose. Staging a *device* change for a file that keeps its path is not
233
- * something a test can do on a real filesystem, and a check that can only be exercised in
234
- * production is a check nobody knows works — a fake identity states each case directly.
235
- */
236
- export function isUnchangedAttachment(recorded, observed) {
237
- return observed.isRegularFile
238
- && observed.canonicalPath === recorded.filePath
239
- && observed.dev === recorded.dev
240
- && observed.ino === recorded.ino
241
- && observed.size === recorded.size;
242
- }
243
- /**
244
- * Phase 1 of `claim()`: synchronously reserves `attachments` for `runId`, or throws (releasing
245
- * whatever it already reserved this call) the first time a requested attachment turns out to be
246
- * unknown or already claimed.
247
- *
248
- * The reservation loop deliberately has no `await`: this store's exactly-once guarantee is what
249
- * stops two runs being handed the same real path on disk, and `claim` is reachable concurrently
250
- * (two run starts, one shared attachment). Nothing between `records.get` and the assignment of
251
- * `record.claimedRunId` may ever become asynchronous — that window is exactly where a concurrent
252
- * call would get its turn and could observe the same record as still unclaimed.
253
- *
254
- * Exported so this invariant can be exercised directly against a plain `Map` of fabricated
255
- * records, without going through a disk-backed store.
256
- */
257
- export function reserveAttachmentRecords(attachments, records, runId, maxAttachments) {
258
- if (attachments.length > maxAttachments) {
259
- throw new AttachmentRejectedError('too-many-attachments', 'Too many attachments');
260
- }
261
- const requestedPaths = new Set(attachments.map((attachment) => attachment.path));
262
- if (requestedPaths.size !== attachments.length) {
263
- throw new AttachmentRejectedError('duplicate-attachment', 'Duplicate attachment');
264
- }
265
- const claimed = [];
266
- for (const requested of attachments) {
267
- const record = records.get(requested.path);
268
- if (!record || record.claimedRunId !== undefined) {
269
- for (const reserved of claimed)
270
- delete reserved.claimedRunId;
271
- throw new AttachmentRejectedError('attachment-unknown-or-claimed', 'Attachment is unknown or already claimed');
272
- }
273
- record.claimedRunId = runId;
274
- claimed.push(record);
275
- }
276
- return claimed;
277
- }
278
- /**
279
- * Phase 2 of `claim()`: re-verifies every already-reserved record against the filesystem — not
280
- * merely re-read, but re-checked against what registration recorded, so someone able to write into
281
- * the batch directory between upload and run start cannot get the agent to read a file of their
282
- * choosing — and checks every claimed attachment shares one batch. Returns the shared batch
283
- * directory on success (or `''` for an empty `claimed`, which `claim()` never passes in — it
284
- * returns before calling this — but which a direct caller can still treat as "no batch").
285
- *
286
- * Throws without releasing `claimed`'s reservations; releasing is the caller's job (`claim`'s own
287
- * `catch`), so a rejected claim still leaves nothing half-claimed and the caller can retry with a
288
- * corrected set.
289
- *
290
- * Exported so the integrity and mixed-batch checks can be exercised directly against fabricated
291
- * records over real files on disk, without a full `createDiskAttachmentStore` around them.
292
- */
293
- export async function verifyClaimedAttachments(claimed) {
294
- let batchDirectory = '';
295
- for (const [index, record] of claimed.entries()) {
296
- const info = await lstat(record.filePath);
297
- const canonicalPath = await realpath(record.filePath);
298
- if (!isUnchangedAttachment(record, {
299
- isRegularFile: info.isFile(),
300
- dev: info.dev,
301
- ino: info.ino,
302
- size: info.size,
303
- canonicalPath,
304
- })) {
305
- throw new AttachmentRejectedError('attachment-integrity', 'Attachment changed after upload');
306
- }
307
- if (index > 0 && record.batchDirectory !== batchDirectory) {
308
- throw new AttachmentRejectedError('mixed-batch', 'Attachments must belong to one batch');
309
- }
310
- batchDirectory = record.batchDirectory;
311
- }
312
- return batchDirectory;
313
- }
314
- /** Renders a byte cap the way a person would read it, for a message a user actually sees. */
315
- function formatByteLimit(bytes) {
316
- const megabytes = bytes / (1024 * 1024);
317
- return Number.isInteger(megabytes) ? `${megabytes} MB` : `${bytes} bytes`;
318
- }
319
- /**
320
- * Reduces an untrusted upload filename to a display-only basename over a conservative allowlist.
321
- * Never used as the name of the stored file — see this module's trust-model doc.
322
- */
323
- export function sanitizeAttachmentName(requestedName) {
324
- if (typeof requestedName !== 'string')
325
- return 'attachment';
326
- return basename(requestedName).replaceAll(/[^a-zA-Z0-9._ -]/gu, '_') || 'attachment';
327
- }
328
- /** `true` when `body`'s first 8 bytes are the PNG signature. */
329
- export function hasPngSignature(body) {
330
- return body.length >= 8
331
- && body[0] === 0x89
332
- && body[1] === 0x50
333
- && body[2] === 0x4e
334
- && body[3] === 0x47;
335
- }
336
- /** `true` when `body`'s first 3 bytes are the JPEG start-of-image marker. */
337
- export function hasJpegSignature(body) {
338
- return body.length >= 3
339
- && body[0] === 0xff
340
- && body[1] === 0xd8
341
- && body[2] === 0xff;
342
- }
343
- /** `true` when `body`'s first 6 bytes spell either GIF version tag. */
344
- export function hasGifSignature(body) {
345
- const signature = new TextDecoder().decode(body.slice(0, 6));
346
- return signature === 'GIF87a' || signature === 'GIF89a';
347
- }
348
- /** `true` when `body` opens with a RIFF container whose form type is WEBP. */
349
- export function hasWebpSignature(body) {
350
- return body.length >= 12
351
- && new TextDecoder().decode(body.slice(0, 4)) === 'RIFF'
352
- && new TextDecoder().decode(body.slice(8, 12)) === 'WEBP';
353
- }
354
- /** Every recognized image signature, checked in this order until one matches. */
355
- const IMAGE_SIGNATURE_MATCHERS = [
356
- hasPngSignature,
357
- hasJpegSignature,
358
- hasGifSignature,
359
- hasWebpSignature,
360
- hasAvifSignature,
361
- ];
362
- /**
363
- * Infers `'image'` from the leading bytes rather than from a renderer-controlled MIME type or file
364
- * extension. PNG, JPEG, GIF87a/89a, WEBP, and AVIF (brand-checked ISO-BMFF, see
365
- * {@link hasAvifSignature}) are recognized; everything else is `'file'` — including a plain MP4 or
366
- * other non-AVIF ISO-BMFF file, which shares AVIF's `ftyp` tag but is deliberately NOT matched here
367
- * (see {@link hasIsoBmffFtypTag}'s doc for why a brand-blind `ftyp` check would be wrong).
368
- *
369
- * `kind` decides whether a path is later passed to `AgentExecutor.run()`'s `imagePaths`, so letting
370
- * a renderer assert it would let a renderer choose how the agent runtime parses the bytes.
371
- */
372
- export function detectAttachmentKind(body) {
373
- return IMAGE_SIGNATURE_MATCHERS.some((matchesSignature) => matchesSignature(body)) ? 'image' : 'file';
374
- }
375
- /**
376
- * Streams a request body straight to a private file under a hard byte cap, keeping only the
377
- * leading signature bytes in memory so an upload never costs memory proportional to its size.
378
- *
379
- * Opened `wx`, so this can never overwrite an existing file. A partial write is removed before the
380
- * rejection propagates: the cap is enforced *during* the stream, which necessarily means some bytes
381
- * already reached disk by the time it trips.
382
- */
383
- export async function writeBoundedAttachmentBody({ request, filePath, maxBytes, mode = 0o600, }) {
384
- const handle = await open(filePath, 'wx', mode);
385
- let total = 0;
386
- let signature = Buffer.alloc(0);
387
- try {
388
- for await (const chunk of request) {
389
- const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk));
390
- total += buffer.byteLength;
391
- if (total > maxBytes) {
392
- throw new AttachmentRejectedError('attachment-too-large', `Each attachment must be ${formatByteLimit(maxBytes)} or smaller`);
393
- }
394
- if (signature.byteLength < SIGNATURE_BYTES) {
395
- signature = Buffer.concat([signature, buffer.subarray(0, SIGNATURE_BYTES - signature.byteLength)], Math.min(SIGNATURE_BYTES, signature.byteLength + buffer.byteLength));
396
- }
397
- await handle.write(buffer);
398
- }
399
- await handle.close();
400
- await chmod(filePath, mode);
401
- return { size: total, signature };
402
- }
403
- catch (error) {
404
- // Reached both while the handle is still open (the byte cap tripped, or the request stream
405
- // errored) and after it was already closed (`chmod` failed). No `.catch` is needed to tell those
406
- // apart: Node's `FileHandle.close()` is idempotent — closing an already-closed handle resolves
407
- // — so this can only reject for a handle that is genuinely still open and unclosable, which is
408
- // a failure worth surfacing rather than swallowing.
409
- await handle.close();
410
- await rm(filePath, { force: true });
411
- throw error;
412
- }
413
- }
414
- // ---------------------------------------------------------------------------
415
- // Restart survival (`retainAcrossRestarts`)
416
- // ---------------------------------------------------------------------------
417
- /**
418
- * Directory, directly under the upload root, holding one small JSON sidecar per registered
419
- * attachment. This is what makes a restart-surviving store possible at all: the upload path encodes
420
- * the batch id and nothing else, so a directory scan alone can never recover an attachment's
421
- * display `name`, its sniffed `kind`, its capability `id`, or — the one that decides whether
422
- * `listPendingForOwner` can see it again — its `ownerId`. A scan-only "reconstruct from the paths"
423
- * design therefore brings the *bytes* back and still shows the user an empty list, which is half a
424
- * fix.
425
- *
426
- * The leading `.` is load-bearing: `BATCH_ID_PATTERN` admits no `.`, so `resolveBatchDirectory` can
427
- * never produce this path and a batch can never collide with (or be made to write into) the sidecar
428
- * directory. It also sits OUTSIDE every batch directory on purpose — a batch directory is the one
429
- * directory a host grants the agent read access to (`AttachmentClaim.batchDirectory`), so sidecars
430
- * kept next to their files would hand a run the `ownerId` and capability ids of every other
431
- * attachment in the same batch.
432
- */
433
- const SIDECAR_DIRECTORY_NAME = '.records';
434
- /** Field types a sidecar must carry, checked as data so the validator stays one flat loop. */
435
- const PERSISTED_FIELD_TYPES = {
436
- id: 'string',
437
- filePath: 'string',
438
- name: 'string',
439
- kind: 'string',
440
- size: 'number',
441
- batchId: 'string',
442
- dev: 'number',
443
- ino: 'number',
444
- createdAt: 'number',
445
- };
446
- function hasPersistedFieldTypes(candidate) {
447
- return Object.entries(PERSISTED_FIELD_TYPES)
448
- .every(([field, type]) => typeof candidate[field] === type);
449
- }
450
- function isPersistedAttachmentShape(raw) {
451
- if (typeof raw !== 'object' || raw === null)
452
- return false;
453
- const candidate = raw;
454
- if (!hasPersistedFieldTypes(candidate))
455
- return false;
456
- if (candidate.ownerId !== undefined && typeof candidate.ownerId !== 'string')
457
- return false;
458
- return candidate.kind === 'image' || candidate.kind === 'file';
459
- }
460
- /**
461
- * Turns one sidecar's parsed JSON back into an `AttachmentRecord`, or `undefined` for anything that
462
- * is not a well-formed record naming a file inside its own batch directory.
463
- *
464
- * `batchDirectory` is re-derived here and `filePath`'s containment is re-checked against it with
465
- * the same parent-equality test `register` uses — the two checks that make an adopted record no
466
- * more trusted than one this process registered itself. Pure and exported so both can be exercised
467
- * against hostile input directly, without staging files on disk.
468
- */
469
- export function parsePersistedAttachment(raw, canonicalUploadDirectory) {
470
- if (!isPersistedAttachmentShape(raw))
471
- return undefined;
472
- if (!BATCH_ID_PATTERN.test(raw.batchId))
473
- return undefined;
474
- const batchDirectory = resolve(canonicalUploadDirectory, raw.batchId);
475
- const filePath = resolve(raw.filePath);
476
- if (dirname(filePath) !== batchDirectory)
477
- return undefined;
478
- return {
479
- id: raw.id,
480
- filePath,
481
- name: raw.name,
482
- kind: raw.kind,
483
- size: raw.size,
484
- batchId: raw.batchId,
485
- batchDirectory,
486
- dev: raw.dev,
487
- ino: raw.ino,
488
- createdAt: raw.createdAt,
489
- ...(raw.ownerId === undefined ? {} : { ownerId: raw.ownerId }),
490
- };
491
- }
492
- /**
493
- * Sidecar filename for a record id. Reduces the id to the same `[a-zA-Z0-9-]` allowlist
494
- * `BATCH_ID_PATTERN` uses before appending the extension, so no id — however this store's own id
495
- * format later changes — can put a `/`, a `..`, or a second extension into the path. Ids are
496
- * `attachment:<uuid>`, so the reduction stays injective in practice: the UUID is what makes it
497
- * unique and the UUID survives unchanged.
498
- */
499
- export function attachmentSidecarFileName(id) {
500
- return `${id.replaceAll(/[^a-zA-Z0-9-]/gu, '_')}.json`;
501
- }
502
- async function readPersistedAttachment(sidecarPath, canonicalUploadDirectory) {
503
- try {
504
- const raw = JSON.parse(await readFile(sidecarPath, 'utf8'));
505
- return parsePersistedAttachment(raw, canonicalUploadDirectory);
506
- }
507
- catch {
508
- // Unreadable, truncated by a kill mid-write, or not JSON at all. Indistinguishable from a
509
- // sidecar that never described a real attachment, and handled identically: not adopted.
510
- return undefined;
511
- }
512
- }
513
- /**
514
- * `true` when the file this record describes is still byte-for-byte the file registration accepted.
515
- *
516
- * Deliberately `verifyClaimedAttachments` rather than a looser existence check: adoption must apply
517
- * the SAME `dev`/`ino`/`size`/`realpath` gate `claim()` applies, or a restart would become the one
518
- * moment at which a file swapped underneath the store gets handed to an agent anyway.
519
- */
520
- async function isAdoptableAttachment(record) {
521
- try {
522
- await verifyClaimedAttachments([record]);
523
- return true;
524
- }
525
- catch {
526
- return false;
527
- }
528
- }
529
- /**
530
- * Rebuilds the record map from the sidecar directory, adopting only records that are (a) well
531
- * formed and contained, (b) still within the retention window, and (c) still backed by the exact
532
- * file registration accepted. Anything failing any of those is deleted — sidecar first, then the
533
- * file it named, and the file ONLY when containment passed, so an unparseable sidecar can never
534
- * make this an arbitrary-file-delete primitive for whatever the daemon can unlink.
535
- *
536
- * **The retention consequence, stated rather than assumed harmless.** Because `claimedRunId` is not
537
- * persisted (see {@link PersistedAttachmentRecord}), a file claimed by a run that died with the
538
- * process is adopted as unclaimed instead of being wiped, so it now occupies disk and quota for up
539
- * to `retentionMs` rather than until the next start. Bounded by the same `maxStoredAttachments` /
540
- * `maxStoredBytes` quotas as any live upload, and cleared by the `pruneExpired` every upload
541
- * already runs — but it is a real change in when that disk comes back.
542
- *
543
- * @complexity O(n) in sidecars present, each costing one read and one `lstat`/`realpath` pair.
544
- */
545
- export async function loadPersistedAttachments({ canonicalUploadDirectory, retentionMs, now = Date.now(), }) {
546
- const sidecarDirectory = resolve(canonicalUploadDirectory, SIDECAR_DIRECTORY_NAME);
547
- await mkdir(sidecarDirectory, { recursive: true, mode: 0o700 });
548
- const adopted = new Map();
549
- for (const entry of await readdir(sidecarDirectory)) {
550
- const sidecarPath = resolve(sidecarDirectory, entry);
551
- const record = await readPersistedAttachment(sidecarPath, canonicalUploadDirectory);
552
- if (record && now - record.createdAt < retentionMs && await isAdoptableAttachment(record)) {
553
- adopted.set(record.id, record);
554
- continue;
555
- }
556
- await rm(sidecarPath, { force: true });
557
- if (record)
558
- await rm(record.filePath, { force: true });
559
- }
560
- return adopted;
561
- }
562
- /** Deletes everything in one batch directory that no adopted record names, then tidies the
563
- * directory away if that emptied it. A root entry that is not a directory at all is removed
564
- * outright — the store never creates one, so it can only be debris. */
565
- async function removeUnadoptedBatch(batchDirectory, keep) {
566
- const entries = await readdir(batchDirectory).catch(() => undefined);
567
- if (entries === undefined) {
568
- await rm(batchDirectory, { force: true });
569
- return;
570
- }
571
- for (const entry of entries) {
572
- const filePath = resolve(batchDirectory, entry);
573
- if (!keep.has(filePath))
574
- await rm(filePath, { recursive: true, force: true });
575
- }
576
- await rmdir(batchDirectory).catch(() => undefined);
577
- }
578
- /**
579
- * Removes every upload the sidecar pass did not adopt. Without this, a file whose sidecar was lost
580
- * (or was never written, because it predates this option) would survive forever with nothing
581
- * tracking it — trading the wipe's data loss for unbounded disk growth, which is not a trade worth
582
- * making. This is what keeps "never wipe on construction" bounded.
583
- */
584
- export async function removeUnadoptedUploads(canonicalUploadDirectory, adopted) {
585
- const keep = new Set([...adopted.values()].map((record) => record.filePath));
586
- for (const entry of await readdir(canonicalUploadDirectory)) {
587
- if (entry === SIDECAR_DIRECTORY_NAME)
588
- continue;
589
- await removeUnadoptedBatch(resolve(canonicalUploadDirectory, entry), keep);
590
- }
591
- }
592
- /**
593
- * Decides what a newly-constructed store starts holding: nothing (the default — empty the directory
594
- * outright, this pack's behavior before `retainAcrossRestarts` existed), or the authenticated
595
- * survivors of the previous process.
596
- *
597
- * Exported so the whole restart decision can be exercised without standing a store up around it.
598
- */
599
- export async function prepareAttachmentStorage({ canonicalUploadDirectory, retainAcrossRestarts, retentionMs, now, }) {
600
- if (!retainAcrossRestarts) {
601
- for (const entry of await readdir(canonicalUploadDirectory)) {
602
- await rm(resolve(canonicalUploadDirectory, entry), { recursive: true, force: true });
603
- }
604
- return new Map();
605
- }
606
- const adopted = await loadPersistedAttachments({
607
- canonicalUploadDirectory,
608
- retentionMs,
609
- ...(now === undefined ? {} : { now }),
610
- });
611
- await removeUnadoptedUploads(canonicalUploadDirectory, adopted);
612
- return adopted;
613
- }
614
- /**
615
- * The disk-backed `AttachmentStore` this package ships. Every default matches what a chat composer
616
- * needs out of the box; a host that wants different quotas passes them rather than reimplementing
617
- * the port.
618
- *
619
- * @complexity `register`/`claim` are O(n) in the number of tracked records (a small bounded number
620
- * — `maxStoredAttachments`), which is what keeps the quota decision synchronous; see `register`.
621
- */
622
- export async function createDiskAttachmentStore({ uploadDirectory, maxAttachments = 10, maxBatchBytes = 50 * 1024 * 1024, maxStoredAttachments = 100, maxStoredBytes = 200 * 1024 * 1024, retentionMs = 60 * 60 * 1_000, retainAcrossRestarts = false, }) {
623
- await mkdir(uploadDirectory, { recursive: true, mode: 0o700 });
624
- await chmod(uploadDirectory, 0o700);
625
- const canonicalUploadDirectory = await realpath(uploadDirectory);
626
- // Either empties the directory (the default — a file left by an interrupted previous process has
627
- // no record to authenticate it against) or adopts the previous process's authenticated survivors.
628
- // See `prepareAttachmentStorage`.
629
- const records = await prepareAttachmentStorage({
630
- canonicalUploadDirectory,
631
- retainAcrossRestarts,
632
- retentionMs,
633
- });
634
- const sidecarDirectory = resolve(canonicalUploadDirectory, SIDECAR_DIRECTORY_NAME);
635
- const sidecarPathFor = (record) => resolve(sidecarDirectory, attachmentSidecarFileName(record.id));
636
- /**
637
- * Writes one record's sidecar, or does nothing at all when this store was not asked to survive
638
- * restarts. A failure rolls the record back out of the map before propagating: a registration
639
- * whose sidecar could not be written would otherwise be silently non-surviving, which is the
640
- * exact failure mode this whole option exists to remove. `register`'s own `catch` deletes the
641
- * file, so the caller sees a failed upload rather than one that quietly evaporates later.
642
- */
643
- const persistRecord = async (record) => {
644
- if (!retainAcrossRestarts)
645
- return;
646
- const persisted = {
647
- id: record.id,
648
- filePath: record.filePath,
649
- name: record.name,
650
- kind: record.kind,
651
- size: record.size,
652
- batchId: record.batchId,
653
- dev: record.dev,
654
- ino: record.ino,
655
- createdAt: record.createdAt,
656
- ...(record.ownerId === undefined ? {} : { ownerId: record.ownerId }),
657
- };
658
- try {
659
- await writeFile(sidecarPathFor(record), JSON.stringify(persisted), { mode: 0o600 });
660
- }
661
- catch (error) {
662
- records.delete(record.id);
663
- throw error;
664
- }
665
- };
666
- const forgetRecord = async (record) => {
667
- if (retainAcrossRestarts)
668
- await rm(sidecarPathFor(record), { force: true });
669
- };
670
- const resolveBatchDirectory = (batchId) => {
671
- if (!BATCH_ID_PATTERN.test(batchId)) {
672
- throw new AttachmentRejectedError('invalid-batch', 'Invalid attachment batch');
673
- }
674
- // No containment re-check follows, and two things together are why — **both** are load-bearing:
675
- // `BATCH_ID_PATTERN` admits only `[a-zA-Z0-9-]`, so `batchId` carries no `.`, `/`, or `\`; and
676
- // `resolve` normalizes, so the result is exactly `<canonicalUploadDirectory><sep><batchId>`, one
677
- // non-traversing segment deeper. Weakening the pattern (a `.` would be enough) or dropping the
678
- // `resolve` reintroduces traversal here. Verified by sweeping 5,040,504 `(uploadRoot, batchId)`
679
- // pairs on both posix and win32: zero escape the upload root.
680
- return resolve(canonicalUploadDirectory, batchId);
681
- };
682
- const removeEmptyBatch = async (batchDirectory) => {
683
- try {
684
- await rmdir(batchDirectory);
685
- }
686
- catch {
687
- // Non-empty (another unclaimed upload still occupies it) or already gone. Both are fine:
688
- // this is opportunistic tidying, never the thing that makes a delete correct.
689
- }
690
- };
691
- const deleteRecord = async (record) => {
692
- records.delete(record.id);
693
- await forgetRecord(record);
694
- await rm(record.filePath, { force: true });
695
- await removeEmptyBatch(record.batchDirectory);
696
- };
697
- const totalBytes = (candidates) => candidates.reduce((total, record) => total + record.size, 0);
698
- return {
699
- async createBatchDirectory(batchId) {
700
- const directory = resolveBatchDirectory(batchId);
701
- await mkdir(directory, { recursive: true, mode: 0o700 });
702
- await chmod(directory, 0o700);
703
- return directory;
704
- },
705
- async register(input) {
706
- const batchDirectory = resolveBatchDirectory(input.batchId);
707
- // `resolve` is NOT redundant with the route's own `resolve`, and this line is the precondition
708
- // the containment argument below depends on. Do not remove it or take a pre-resolved path from
709
- // the caller: `register` is a public port method, so `input.path` is untrusted.
710
- const filePath = resolve(input.path);
711
- // Containment: the file's parent directory must be *exactly* the batch directory — stronger
712
- // than a `path.relative`-based "is inside" test, which also admits nested subdirectories and
713
- // the batch directory itself.
714
- //
715
- // Why parent-equality is sufficient: `resolve` above guarantees `filePath` is absolute and
716
- // normalized with no `..` left in the path body, so `dirname(filePath) === batchDirectory`
717
- // implies `filePath` is `batchDirectory + sep + basename` with a real, non-traversing
718
- // basename. This is *not* an unconditional path-algebra identity — without the `resolve`,
719
- // `dirname('/a/..') === '/a'` is true while `/a/..` escapes `/a`. The normalization is what
720
- // makes the argument hold; a differential fuzz of 6,000,000 `input.path` values against the
721
- // previous two-part check found zero inputs this accepts that containment rejected.
722
- //
723
- // Deliberately OUTSIDE the `try` below, whose `catch` unlinks `filePath`. A path that failed
724
- // containment must never reach that cleanup, or this port becomes an arbitrary-file-delete
725
- // primitive for anything the daemon can unlink.
726
- if (dirname(filePath) !== batchDirectory) {
727
- throw new AttachmentRejectedError('attachment-integrity', 'Attachment path is outside its batch');
728
- }
729
- try {
730
- const info = await lstat(filePath);
731
- // `lstat` (not `stat`): a symlink must be seen as a symlink, not followed. `isFile()` is
732
- // false for a symlink and for a directory, which is the whole check.
733
- if (!info.isFile()) {
734
- throw new AttachmentRejectedError('attachment-integrity', 'Attachment is not a regular file');
735
- }
736
- const canonical = await realpath(filePath);
737
- if (canonical !== filePath) {
738
- throw new AttachmentRejectedError('attachment-integrity', 'Attachment path is not canonical');
739
- }
740
- // Quotas are decided here, immediately before `records.set`, with no `await` in between —
741
- // so two concurrent registrations cannot both observe the last free slot (or the last free
742
- // bytes) and both commit. Moving any of this above the `await`s would reintroduce that
743
- // race; adding an `await` below would too.
744
- const batchRecords = [...records.values()]
745
- .filter((record) => record.batchId === input.batchId);
746
- if (batchRecords.length >= maxAttachments) {
747
- throw new AttachmentRejectedError('batch-count-exceeded', `You can attach at most ${maxAttachments} files to one message`);
748
- }
749
- if (totalBytes(batchRecords) + info.size > maxBatchBytes) {
750
- throw new AttachmentRejectedError('batch-too-large', `Attachments for one message must total ${formatByteLimit(maxBatchBytes)} or less`);
751
- }
752
- if (records.size >= maxStoredAttachments
753
- || totalBytes([...records.values()]) + info.size > maxStoredBytes) {
754
- throw new AttachmentRejectedError('storage-full', 'Attachment storage is full');
755
- }
756
- const id = `attachment:${randomUUID()}`;
757
- const record = {
758
- id,
759
- filePath,
760
- name: input.name,
761
- kind: input.kind,
762
- size: info.size,
763
- batchId: input.batchId,
764
- batchDirectory,
765
- dev: info.dev,
766
- ino: info.ino,
767
- createdAt: Date.now(),
768
- ...(input.ownerId === undefined ? {} : { ownerId: input.ownerId }),
769
- };
770
- records.set(id, record);
771
- // The first `await` after the synchronous quota window closes, so it cannot reopen the race
772
- // the comment above guards. Rolls `records` back itself on failure — see `persistRecord`.
773
- await persistRecord(record);
774
- return { path: id, name: record.name, kind: record.kind, size: record.size };
775
- }
776
- catch (error) {
777
- // A file this store refused to take ownership of must not be left behind. `rm` is
778
- // deliberately non-recursive (never recurse over an attacker-influenced path) and its own
779
- // failure is swallowed, so the real rejection above always propagates instead of being
780
- // masked by e.g. EISDIR from a directory sitting at `filePath`.
781
- await rm(filePath, { force: true }).catch(() => undefined);
782
- await removeEmptyBatch(batchDirectory);
783
- throw error;
784
- }
785
- },
786
- async claim(attachments, runId) {
787
- if (attachments.length === 0)
788
- return { attachments: [] };
789
- // Phase 1 (`reserveAttachmentRecords`) reserves synchronously; Phase 2
790
- // (`verifyClaimedAttachments`) re-validates what is now held exclusively. Any Phase 2 failure
791
- // releases the whole reservation here, so a rejected claim still leaves nothing half-claimed
792
- // and the caller can retry with a corrected set. Only reservations made by *this* call are
793
- // released, so a concurrent winner's claim is never revoked by a loser's rollback.
794
- const claimed = reserveAttachmentRecords(attachments, records, runId, maxAttachments);
795
- try {
796
- const batchDirectory = await verifyClaimedAttachments(claimed);
797
- return {
798
- attachments: claimed.map((record) => ({
799
- path: record.filePath,
800
- name: record.name,
801
- kind: record.kind,
802
- size: record.size,
803
- })),
804
- batchDirectory,
805
- };
806
- }
807
- catch (error) {
808
- for (const record of claimed)
809
- delete record.claimedRunId;
810
- throw error;
811
- }
812
- },
813
- async resolveForRun(ref, runId) {
814
- // Synchronous check-then-reserve, same reasoning as `reserveAttachmentRecords`: nothing may
815
- // `await` between reading `claimedRunId` and writing it, or a concurrent call could observe
816
- // the same unclaimed record and both believe they reserved it.
817
- const record = records.get(ref) ?? [...records.values()].find((candidate) => candidate.filePath === ref);
818
- if (!record)
819
- return undefined;
820
- if (record.claimedRunId !== undefined && record.claimedRunId !== runId) {
821
- throw new AttachmentRejectedError('attachment-unknown-or-claimed', 'Attachment is unknown or already claimed');
822
- }
823
- const reservedNow = record.claimedRunId === undefined;
824
- if (reservedNow)
825
- record.claimedRunId = runId;
826
- try {
827
- await verifyClaimedAttachments([record]);
828
- }
829
- catch (error) {
830
- // Mirrors `claim()`'s own rollback: a lookup that fails integrity must not leave a phantom
831
- // reservation behind for a record that turned out to be unsafe to hand back.
832
- if (reservedNow)
833
- delete record.claimedRunId;
834
- throw error;
835
- }
836
- return { path: record.filePath, name: record.name, kind: record.kind, size: record.size };
837
- },
838
- async listPendingForOwner(ownerId) {
839
- return [...records.values()]
840
- // `record.ownerId !== undefined` first, short-circuiting before the comparison: this is
841
- // what makes an ownerless record excluded rather than accidentally matched by a falsy-ish
842
- // `ownerId` argument — see this method's own doc on why that must never be a wildcard.
843
- .filter((record) => record.claimedRunId === undefined && record.ownerId !== undefined && record.ownerId === ownerId)
844
- .sort((a, b) => a.createdAt - b.createdAt)
845
- .map((record) => ({ ref: record.id, name: record.name, kind: record.kind, size: record.size, createdAt: record.createdAt }));
846
- },
847
- async deleteUnclaimed(batchId, paths) {
848
- const batchDirectory = resolveBatchDirectory(batchId);
849
- for (const attachmentId of new Set(paths)) {
850
- const record = records.get(attachmentId);
851
- if (record && record.batchId === batchId && record.claimedRunId === undefined) {
852
- await deleteRecord(record);
853
- }
854
- }
855
- await removeEmptyBatch(batchDirectory);
856
- },
857
- async cleanupRun(runId) {
858
- for (const record of [...records.values()]) {
859
- if (record.claimedRunId === runId)
860
- await deleteRecord(record);
861
- }
862
- },
863
- async pruneExpired(now = Date.now()) {
864
- for (const record of [...records.values()]) {
865
- if (record.claimedRunId === undefined && now - record.createdAt >= retentionMs) {
866
- await deleteRecord(record);
867
- }
868
- }
869
- },
870
- async dispose() {
871
- for (const record of [...records.values()])
872
- await deleteRecord(record);
873
- },
874
- };
875
- }
876
- export const ATTACHMENTS_ROUTE_PATH = '/api/attachments';
877
- function defaultInternalErrorSink(context) {
878
- // eslint-disable-next-line no-console
879
- console.error(`[@jini-ai/http-kit] internal error (${context.source}, correlationId=${context.correlationId})`, context.error);
880
- }
881
- function reportInternalError(deps, source, error, batchId) {
882
- const correlationId = randomUUID();
883
- const sink = deps.onInternalError ?? defaultInternalErrorSink;
884
- sink({ source, batchId, correlationId, error });
885
- return createApiError('INTERNAL_ERROR', 'an internal error occurred', { requestId: correlationId });
886
- }
887
- /**
888
- * Sends the right status for an upload failure: an explicitly-classified rejection keeps its real
889
- * message (the composer shows it to the user, so "you can attach at most 10 files" has to survive),
890
- * while an integrity failure or any unexpected error is redacted to a generic `INTERNAL_ERROR`.
891
- */
892
- function respondToUploadFailure(res, deps, error, batchId, source) {
893
- if (error instanceof AttachmentRejectedError && REJECTION_STATUS[error.reason] !== 500) {
894
- sendApiError(res, REJECTION_STATUS[error.reason], apiErrorForRejection(error));
895
- return;
896
- }
897
- sendApiError(res, 500, reportInternalError(deps, source, error, batchId));
898
- }
899
- /** `false` when the same-origin guard rejected the request (and already answered it). */
900
- function passesOriginGuard(req, res, deps, adapter) {
901
- if (deps.requireSameOrigin === false)
902
- return true;
903
- const origin = guardSameOrigin(req, adapter);
904
- if (origin.ok)
905
- return true;
906
- sendApiError(res, 403, origin.error);
907
- return false;
908
- }
909
- /**
910
- * Handles one upload: rate-limit, batch directory, bounded stream to disk, signature sniff,
911
- * register. Exported so a host mounting its own path (or its own framework) can reuse the whole
912
- * body without re-deriving the ordering, which is load-bearing — see the `finally`.
913
- */
914
- export async function handleAttachmentUpload(req, res, deps, state) {
915
- const maxConcurrentUploads = deps.maxConcurrentUploads ?? 4;
916
- const maxAttachmentBytes = deps.maxAttachmentBytes ?? 20 * 1024 * 1024;
917
- const name = sanitizeAttachmentName(req.query.name);
918
- const batchId = typeof req.query.batch === 'string' ? req.query.batch : '';
919
- // Every refusal below goes through `respondToUploadFailure`, so the reason -> status/code mapping
920
- // lives in exactly one place rather than being partly inlined here.
921
- if (state.activeUploads >= maxConcurrentUploads) {
922
- respondToUploadFailure(res, deps, new AttachmentRejectedError('too-many-concurrent-uploads', 'Too many attachment uploads are in progress'), batchId, 'attachment-upload');
923
- return;
924
- }
925
- // Checked before a single byte is written: a drained stream would otherwise produce a zero-byte
926
- // file and the misleading "attachment is empty". See this module's body-parser doc.
927
- if (req.readableEnded) {
928
- respondToUploadFailure(res, deps, new AttachmentRejectedError('attachment-body-consumed', `the request body was already consumed before ${ATTACHMENTS_ROUTE_PATH} received it — mount this route pack before any global body parser, or scope that parser to skip this path`), batchId, 'attachment-upload');
929
- return;
930
- }
931
- state.activeUploads += 1;
932
- try {
933
- await deps.store.pruneExpired();
934
- const batchDirectory = await deps.store.createBatchDirectory(batchId);
935
- // A fresh UUID, never the client's filename. The extension is carried over (bounded) only
936
- // because some agent runtimes decide how to read a file from its suffix.
937
- const suffix = extname(name).slice(0, 12);
938
- const path = resolve(batchDirectory, `${randomUUID()}${suffix}`);
939
- const upload = await writeBoundedAttachmentBody({ request: req, filePath: path, maxBytes: maxAttachmentBytes });
940
- if (upload.size === 0) {
941
- await rm(path, { force: true });
942
- sendApiError(res, 400, createApiError('BAD_REQUEST', 'Attachment is empty'));
943
- return;
944
- }
945
- const ownerId = deps.resolveOwnerId?.(req);
946
- const attachment = await deps.store.register({
947
- batchId,
948
- path,
949
- name,
950
- kind: detectAttachmentKind(upload.signature),
951
- size: upload.size,
952
- ...(ownerId === undefined ? {} : { ownerId }),
953
- });
954
- sendJson(res, 201, { attachment });
955
- }
956
- catch (error) {
957
- respondToUploadFailure(res, deps, error, batchId, 'attachment-upload');
958
- }
959
- finally {
960
- state.activeUploads -= 1;
961
- // Removes the batch directory when this failed upload left it empty. Passing no paths is
962
- // deliberate: a *successful* upload must not be deleted here, and `deleteUnclaimed` with an
963
- // empty list does exactly the directory tidying and nothing else.
964
- await deps.store.deleteUnclaimed(batchId, []).catch(() => undefined);
965
- }
966
- }
967
- /**
968
- * Handles a client abandoning a batch (a failed multi-file upload, a cleared composer). Only
969
- * *unclaimed* uploads can be deleted this way, so a caller cannot use it to pull files out from
970
- * under a run that already claimed them.
971
- */
972
- export async function handleAttachmentCleanup(req, res, deps) {
973
- const maxCleanupPaths = deps.maxCleanupPaths ?? 10;
974
- const body = req.body;
975
- if (typeof body?.batchId !== 'string'
976
- || !Array.isArray(body.paths)
977
- || body.paths.length > maxCleanupPaths
978
- || !body.paths.every((path) => typeof path === 'string')) {
979
- sendApiError(res, 400, createApiError('BAD_REQUEST', 'Invalid attachment cleanup request'));
980
- return;
981
- }
982
- try {
983
- await deps.store.deleteUnclaimed(body.batchId, body.paths);
984
- res.status(204).end();
985
- }
986
- catch (error) {
987
- respondToUploadFailure(res, deps, error, body.batchId, 'attachment-cleanup');
988
- }
989
- }
990
- /**
991
- * Mounts `POST`/`DELETE /api/attachments` on `app`. A pack's `http(app, services)` calls this
992
- * directly.
993
- *
994
- * Hand-mounted rather than built from `defineJsonRoute`/`mountJsonRoute` for two concrete reasons:
995
- * the upload reads the raw request stream (a JSON-parsed `req.body` is exactly what must not have
996
- * happened), and the cleanup answers `204` with no body, which a JSON responder cannot express.
997
- */
998
- export function registerAttachmentRoutes(app, deps, adapter) {
999
- // Per-registration, not module-level: two daemons in one process (a test harness, an embedded
1000
- // second host) must not share one upload budget.
1001
- const state = { activeUploads: 0 };
1002
- app.post(ATTACHMENTS_ROUTE_PATH, async (req, res) => {
1003
- try {
1004
- if (!passesOriginGuard(req, res, deps, adapter))
1005
- return;
1006
- await handleAttachmentUpload(req, res, deps, state);
1007
- }
1008
- catch (error) {
1009
- // `handleAttachmentUpload` already catches everything inside its own body — this only ever
1010
- // fires for `passesOriginGuard`/`guardSameOrigin` throwing, which is Result-returning by
1011
- // contract but not guaranteed never to throw (`isLocalSameOrigin` really does throw on a
1012
- // malformed `JINI_ALLOWED_ORIGINS` entry — see the paired regression test). Mounting this
1013
- // route bypasses `mountJsonRoute`'s adapter (see this function's own doc), so nothing else
1014
- // stood between that throw and an unhandled rejection with no process-level guard anywhere
1015
- // in this package's path.
1016
- if (!res.headersSent)
1017
- respondToUploadFailure(res, deps, error, null, 'attachment-upload');
1018
- }
1019
- });
1020
- app.delete(ATTACHMENTS_ROUTE_PATH, async (req, res) => {
1021
- try {
1022
- if (!passesOriginGuard(req, res, deps, adapter))
1023
- return;
1024
- await handleAttachmentCleanup(req, res, deps);
1025
- }
1026
- catch (error) {
1027
- if (!res.headersSent)
1028
- sendApiError(res, 500, reportInternalError(deps, 'attachment-cleanup', error, null));
1029
- }
1030
- });
1031
- }
1032
- //# sourceMappingURL=attachments.js.map