From eabf12a9cdfb66763b2017da240060f7fee0f2db Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 20:02:42 +0000 Subject: [PATCH 01/10] wip(storage): one upload link takes several files on a multi-file field Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibzVFJSNs6XZjC8jkNJ --- .../src/file-attachment-service.ts | 10 + .../service-storage/src/record-file-access.ts | 433 ++++++++++++++---- .../service-storage/src/storage-routes.ts | 104 ++++- ...e-routes.upload-link-refusal-relay.test.ts | 1 + .../src/storage-service-plugin.ts | 5 +- .../service-storage/src/upload-link-wire.ts | 26 ++ 6 files changed, 492 insertions(+), 87 deletions(-) diff --git a/packages/services/service-storage/src/file-attachment-service.ts b/packages/services/service-storage/src/file-attachment-service.ts index 1b2c8e123d5..c47c7b427e6 100644 --- a/packages/services/service-storage/src/file-attachment-service.ts +++ b/packages/services/service-storage/src/file-attachment-service.ts @@ -54,6 +54,7 @@ import { type RecordFileRead, type RecordFileTarget, type UploadLinkDoor, + type UploadLinkFilesOutcome, type UploadLinkGrant, type UploadLinkOutcome, type UploadLinkTarget, @@ -379,6 +380,15 @@ export class FileAttachmentService return this.recordFilesOrRefuse().consumeUploadLink(token, upload, callerUserId); } + /** [#32747] One submit carrying several files, for a link to a multi-file field. */ + async consumeUploadLinkFiles( + token: string, + uploads: UploadLinkUpload[], + callerUserId: string, + ): Promise { + return this.recordFilesOrRefuse().consumeUploadLinkFiles(token, uploads, callerUserId); + } + async attachFile(input: AttachFileInput): Promise { return this.attach(input, null); } diff --git a/packages/services/service-storage/src/record-file-access.ts b/packages/services/service-storage/src/record-file-access.ts index d7c08779813..7113e0ba263 100644 --- a/packages/services/service-storage/src/record-file-access.ts +++ b/packages/services/service-storage/src/record-file-access.ts @@ -41,7 +41,10 @@ import { // The upload doors' own storage-key layout, and the download doors' link. import { buildKey, mintDownloadUrl } from './storage-routes.js'; import { + UPLOAD_LINK_FILE_COUNT_CODE, + UPLOAD_LINK_FILE_COUNT_STATUS, UPLOAD_LINK_KIND, + UPLOAD_LINK_MAX_FILES, UPLOAD_LINK_SEGMENT, UPLOAD_LINK_UNUSABLE_CODE, UPLOAD_LINK_UNUSABLE_MESSAGE, @@ -148,6 +151,32 @@ import { assertFileConstraints } from './file-reference-lifecycle.js'; * is a committed file no record holds, as an upload the console's form * never saved is; `verify-file-references` reports it. * + * ## Several files through one link + * + * [#32747] Ruling A: a link for a file field declared `multiple: true` takes + * several files in its one submit, at most {@link UPLOAD_LINK_MAX_FILES}. + * A single-file field link and an attachments link take one, as before. + * + * - **One submit spends the link once.** Every file in it is judged before + * the spend: the doors' size verdict for each, and, for a submit carrying + * more than one file, the field's own `accept` / `maxSize` for each. One + * refusal refuses the whole submit, nothing is stored, and the link stays + * usable. A submit carrying one file is judged exactly as it was before + * this rule (the record's write judges the field's constraints). + * - **All or nothing after the spend.** A link naming a record stores every + * file, then writes the field once, appending all of them. When any store + * or the write fails, every file the submit stored is discarded, bytes and + * row, so the record holds what it held before and no row of the submit is + * left. + * - **A link naming no record answers every id when it is minted**: the + * agent asks for `count` files, the link row is the first id and `count - 1` + * reservation rows (`pending`, owned by the caller, holding no bytes) are + * the others. The submit must carry exactly `count` files, each stored + * under its id with the binding a single upload gets. Before the upload a + * reserved id is refused to every write, the uploader's own included, by + * the arms that refuse the link's own id; nothing serves it, because it is + * `pending`; and the pending-upload retention reaps it with the link. + * * ## What counts the upload * * The bytes go through the doors' own size verdict (`max_upload_mb`, 413 @@ -169,6 +198,8 @@ const UPLOAD_LINK_SECRET_BYTES = 32; */ const LINK_NAME_OPEN = 'upload-link'; const LINK_NAME_USED = 'upload-link (used)'; +/** [#32747] A row reserving a later file's id for a link that names no record; never a link itself. */ +const LINK_NAME_RESERVED = 'upload-link (reserved)'; /** The most attachments {@link RecordFileAccess.listRecordFilesAs} lists for one record. */ const ATTACHMENT_LIST_LIMIT = 100; @@ -182,8 +213,13 @@ export type RecordFileTarget = { field: string; fileId?: string } | { attachment /** Where an upload link lands: a file field, or the record's attachments list. */ export type UploadLinkTarget = { field: string } | { attachments: true }; -/** [#32686] Where a link that names no record lands: a file field of the record to be created. */ -export type NewRecordUploadLinkTarget = { field: string }; +/** + * [#32686] Where a link that names no record lands: a file field of the record + * to be created. [#32747] `count`: how many files the user will upload through + * it (1 when absent; more only for a multi-file field, at most + * {@link UPLOAD_LINK_MAX_FILES}); the link answers that many ids. + */ +export type NewRecordUploadLinkTarget = { field: string; count?: number }; /** One file a record carries, as {@link RecordFileAccess.listRecordFilesAs} lists it. */ export interface RecordFileEntry { @@ -232,6 +268,13 @@ export interface UploadLinkView { target: 'field' | 'attachments'; /** [#32686] The link names no record: the file waits for the record the agent creates. */ newRecord?: true; + /** + * [#32747] How many files the link's one submit takes: `{ min: 1, max: 1 }` + * for a single-file field or the attachments list; up to + * {@link UPLOAD_LINK_MAX_FILES} for a multi-file field of a record; exactly + * the count asked for, for a link that names no record. + */ + files: { min: number; max: number }; } /** @@ -254,6 +297,18 @@ export interface NewRecordUploadLinkGrant { fileIds: string[]; } +/** [#32747] Where one submit's files landed, in the order they were sent. */ +export interface UploadLinkFilesOutcome { + object: string; + /** The record they landed on; absent for a link that names no record ([#32686]). */ + recordId?: string; + /** The file field they now fill, for a field link. */ + field?: string; + /** The `sys_attachment` row, for an attachments link (which takes one file). */ + attachmentId?: string; + files: Array<{ fileId: string; size: number }>; +} + /** One upload arriving through a link. */ export interface UploadLinkUpload { filename: string; @@ -322,6 +377,11 @@ export interface UploadLinkDoor { inspectUploadLink(token: string, callerUserId: string): Promise; /** Spend the link on `upload`, landing it where the link is bound. */ consumeUploadLink(token: string, upload: UploadLinkUpload, callerUserId: string): Promise; + /** + * [#32747] Spend the link on one submit carrying `uploads` (in the order + * picked), landing all of them where the link is bound, or none. + */ + consumeUploadLinkFiles(token: string, uploads: UploadLinkUpload[], callerUserId: string): Promise; } /** The data-engine surface these verbs use: the reads and writes every engine has, plus its schema read. */ @@ -383,6 +443,9 @@ export interface RecordFileAccessDeps { now?(): number; } +/** [#32747] One upload of a submit, its media type settled. */ +type TypedUpload = UploadLinkUpload & { mimeType: string }; + /** What a link row's `metadata` binds the link to, every value a string (`sys_file.metadata` is a JSON object of strings). */ interface UploadLinkState { kind: typeof UPLOAD_LINK_KIND; @@ -395,6 +458,12 @@ interface UploadLinkState { field?: string; user_id: string; organization_id?: string; + /** + * [#32747] A link that names no record and takes several files: the ids + * reserved for the second file on, comma-separated, in order (the link + * row's own id is the first). + */ + reserved_ids?: string; } /** An ADR-0112-enveloped refusal: `code` and `status` on the thrown error. */ @@ -485,9 +554,63 @@ function openLinkStateOf(row: FileRecord | null): UploadLinkState | null { // [#32686] Only a field link may name no record: an attachment needs its record. if (s.target === 'attachments' && !nonEmptyString(s.record_id)) return null; if (s.record_id !== undefined && !nonEmptyString(s.record_id)) return null; + // [#32747] Reserved ids only on a field link that names no record. + if (s.reserved_ids !== undefined) { + if (s.target !== 'field' || s.record_id !== undefined || typeof s.reserved_ids !== 'string') return null; + const ids = s.reserved_ids.split(','); + if (ids.length < 1 || ids.length >= UPLOAD_LINK_MAX_FILES || !ids.every((id) => LINK_ID.test(id))) return null; + } return s as UploadLinkState; } +/** [#32747] The ids a link that names no record reserved beyond its own, in order. */ +function reservedIdsOf(state: UploadLinkState): string[] { + return state.reserved_ids === undefined ? [] : state.reserved_ids.split(','); +} + +/** [#32747] `sys_file.metadata` of a reservation row: the link it belongs to, and the slot. */ +function reservationMetadata(state: UploadLinkState, linkId: string): string { + return JSON.stringify({ + kind: UPLOAD_LINK_KIND, + link_id: linkId, + object: state.object, + target: 'field', + field: state.field, + user_id: state.user_id, + ...(state.organization_id !== undefined ? { organization_id: state.organization_id } : {}), + }); +} + +/** [#32747] Is `row` still the reservation `linkId` made for its user, holding nothing? */ +function isOpenReservation(row: FileRecord | null, linkId: string, userId: string): boolean { + if (!row || row.status !== 'pending' || row.name !== LINK_NAME_RESERVED || row.owner_id !== userId) return false; + if (typeof row.metadata !== 'string') return false; + try { + const s = JSON.parse(row.metadata) as Record | null; + return !!s && s.kind === UPLOAD_LINK_KIND && s.link_id === linkId && s.user_id === userId && s.target === 'field'; + } catch { + return false; + } +} + +/** + * [#32747] The refusal of a submit carrying a number of files the link does + * not take, before the link is spent. + */ +function refuseFileCount(range: { min: number; max: number }, sent: number): never { + const taken = + range.max === 1 + ? 'takes one file' + : range.min === range.max + ? `takes exactly ${range.min} files, sent together` + : `takes up to ${range.max} files, sent together`; + refuse( + UPLOAD_LINK_FILE_COUNT_CODE, + UPLOAD_LINK_FILE_COUNT_STATUS, + `Nothing was stored: this upload link ${taken}, and ${sent} ${sent === 1 ? 'was' : 'were'} sent.`, + ); +} + /** `sys_file.metadata` for a link's binding. */ function linkMetadata(state: UploadLinkState): string { return JSON.stringify({ @@ -500,6 +623,7 @@ function linkMetadata(state: UploadLinkState): string { ...(state.field !== undefined ? { field: state.field } : {}), user_id: state.user_id, ...(state.organization_id !== undefined ? { organization_id: state.organization_id } : {}), + ...(state.reserved_ids !== undefined ? { reserved_ids: state.reserved_ids } : {}), }); } @@ -840,14 +964,35 @@ export class RecordFileAccess implements ICallerRecordFileService, UploadLinkDoo if (fieldDef.readonly === true) { refuse('FIELD_NOT_ACCESSIBLE', 403, `You cannot upload a file for ${object}.${field}: the field is read-only.`); } - const link = await this.mintLink(engine, caller, object, undefined, field); + // [#32747] How many files, so the answer can name every id now. + const count = (target as { count?: unknown }).count; + let files = 1; + if (count !== undefined) { + if (typeof count !== 'number' || !Number.isInteger(count) || count < 1 || count > UPLOAD_LINK_MAX_FILES) { + refuse( + 'VALIDATION_ERROR', + 400, + `count is how many files the user will upload through the link: a whole number from 1 to ${UPLOAD_LINK_MAX_FILES}.`, + ); + } + if (count > 1 && fieldDef.multiple !== true) { + refuse( + 'VALIDATION_ERROR', + 400, + `${object}.${field} holds one file, so a link for it takes one: omit count, or name a multi-file field.`, + ); + } + files = count; + } + const reserved = Array.from({ length: files - 1 }, () => randomUUID()); + const link = await this.mintLink(engine, caller, object, undefined, field, reserved); return { token: link.token, path: link.path, expiresAt: link.expiresAt, object, field, - fileIds: [link.id], + fileIds: [link.id, ...reserved], }; } @@ -862,6 +1007,7 @@ export class RecordFileAccess implements ICallerRecordFileService, UploadLinkDoo object: string, recordId: string | undefined, field: string | undefined, + reserved: string[] = [], ): Promise<{ id: string; token: string; path: string; expiresAt: string }> { const organizationId = nonEmptyString(caller.tenantId) ? caller.tenantId : null; const id = randomUUID(); @@ -877,6 +1023,7 @@ export class RecordFileAccess implements ICallerRecordFileService, UploadLinkDoo ...(field !== undefined ? { field } : {}), user_id: caller.userId as string, ...(organizationId !== null ? { organization_id: organizationId } : {}), + ...(reserved.length > 0 ? { reserved_ids: reserved.join(',') } : {}), }; const store = new StorageMetadataStore(engine); await store.createFile( @@ -893,6 +1040,37 @@ export class RecordFileAccess implements ICallerRecordFileService, UploadLinkDoo }, { organizationId }, ); + // [#32747] The later files' ids: rows that hold nothing until the upload. + // A failure here takes the link back, so no link answers ids it lacks. + const made: string[] = []; + try { + for (const reservedId of reserved) { + await store.createFile( + { + id: reservedId, + key: buildKey(FIELD_UPLOAD_SCOPE, reservedId, LINK_NAME_OPEN), + name: LINK_NAME_RESERVED, + size: 0, + scope: FIELD_UPLOAD_SCOPE, + acl: 'private', + status: 'pending', + owner_id: caller.userId as string, + metadata: reservationMetadata(state, id), + }, + { organizationId }, + ); + made.push(reservedId); + } + } catch (err) { + for (const rowId of [id, ...made]) { + try { + await store.deleteFile(rowId, { organizationId }); + } catch { + // A pending row the retention reaps; the refusal is what is thrown. + } + } + throw err; + } const token = `${id}.${secret}`; return { id, token, path: `${this.deps.getBasePath()}/${UPLOAD_LINK_SEGMENT}/${token}`, expiresAt }; } @@ -924,29 +1102,66 @@ export class RecordFileAccess implements ICallerRecordFileService, UploadLinkDoo } async inspectUploadLink(token: string, callerUserId: string): Promise { - const { state } = await this.openLink(new StorageMetadataStore(this.engineOrRefuse()), token, callerUserId); + const engine = this.engineOrRefuse(); + const { state } = await this.openLink(new StorageMetadataStore(engine), token, callerUserId); return { expiresAt: state.expires_at, target: state.target, ...(state.record_id === undefined ? { newRecord: true as const } : {}), + files: this.fileRangeOf(engine, state), }; } + /** + * [#32747] How many files the link's one submit takes. A field link naming + * a record reads the field's declaration now, as its write will. + */ + private fileRangeOf(engine: RecordFileEngine, state: UploadLinkState): { min: number; max: number } { + if (state.target !== 'field') return { min: 1, max: 1 }; + if (state.record_id === undefined) { + const files = 1 + reservedIdsOf(state).length; + return { min: files, max: files }; + } + return fieldDefOf(engine, state.object, state.field as string)?.multiple === true + ? { min: 1, max: UPLOAD_LINK_MAX_FILES } + : { min: 1, max: 1 }; + } + async consumeUploadLink(token: string, upload: UploadLinkUpload, callerUserId: string): Promise { + const outcome = await this.consumeUploadLinkFiles(token, [upload], callerUserId); + const [file] = outcome.files; + return { + object: outcome.object, + ...(outcome.recordId !== undefined ? { recordId: outcome.recordId } : {}), + fileId: file.fileId, + size: file.size, + ...(outcome.field !== undefined ? { field: outcome.field } : {}), + ...(outcome.attachmentId !== undefined ? { attachmentId: outcome.attachmentId } : {}), + }; + } + + async consumeUploadLinkFiles( + token: string, + uploads: UploadLinkUpload[], + callerUserId: string, + ): Promise { const engine = this.engineOrRefuse(); const storage = this.storageOrRefuse(); const store = new StorageMetadataStore(engine); const { row, state } = await this.openLink(store, token, callerUserId); - if (!nonEmptyString(upload.filename)) refuse('VALIDATION_ERROR', 400, 'The upload names no file.'); - if (!Buffer.isBuffer(upload.data)) refuse('VALIDATION_ERROR', 400, 'The upload carries no bytes.'); - // The doors' own size verdict, before the link is spent. - const tooLarge = uploadSizeRefusal( - upload.data.byteLength, - resolveStorageLimits(this.deps.getLimitsSnapshot()).maxUploadBytes, - (n) => `The file is ${n} bytes`, - ); - if (tooLarge !== null) refuse(UPLOAD_TOO_LARGE_CODE, UPLOAD_TOO_LARGE_STATUS, tooLarge); + if (!Array.isArray(uploads) || uploads.length === 0) refuse('VALIDATION_ERROR', 400, 'The upload names no file.'); + // [#32747] As many files as the link takes, before anything else is judged. + const range = this.fileRangeOf(engine, state); + if (uploads.length < range.min || uploads.length > range.max) refuseFileCount(range, uploads.length); + const maxUploadBytes = resolveStorageLimits(this.deps.getLimitsSnapshot()).maxUploadBytes; + for (const upload of uploads) { + if (!nonEmptyString(upload?.filename)) refuse('VALIDATION_ERROR', 400, 'The upload names no file.'); + if (!Buffer.isBuffer(upload.data)) refuse('VALIDATION_ERROR', 400, 'The upload carries no bytes.'); + // The doors' own size verdict, before the link is spent. + const tooLarge = uploadSizeRefusal(upload.data.byteLength, maxUploadBytes, (n) => `The file is ${n} bytes`); + if (tooLarge !== null) refuse(UPLOAD_TOO_LARGE_CODE, UPLOAD_TOO_LARGE_STATUS, tooLarge); + } // The user the link was minted for, resolved now: a grant revoked since // refuses the upload, and the writes below run as them. @@ -960,16 +1175,32 @@ export class RecordFileAccess implements ICallerRecordFileService, UploadLinkDoo ); } - const mimeType = nonEmptyString(upload.mimeType) ? upload.mimeType : 'application/octet-stream'; + const typed: TypedUpload[] = uploads.map((upload) => ({ + ...upload, + mimeType: nonEmptyString(upload.mimeType) ? upload.mimeType : 'application/octet-stream', + })); // [#32686] A link that names no record writes no record now, so nothing // judges the field's own `accept` / `maxSize` until the create does: they // are judged here, before the link is spent, as the record's write would // judge them, and a file the field cannot take is refused with nothing - // stored. + // stored. [#32747] So are they for each file of a submit carrying several: + // one file the field cannot take refuses them all with the link unspent. + // A one-file submit to a record is judged by the record's write, as before. const newRecord = state.record_id === undefined; - if (newRecord) { + if (newRecord || typed.length > 1) { const def = requireFileField(engine, state.object, state.field as string); - assertFileConstraints(def, state.field as string, { name: upload.filename, mime_type: mimeType, size: upload.data.byteLength }); + for (const upload of typed) { + assertFileConstraints(def, state.field as string, { + name: upload.filename, + mime_type: upload.mimeType, + size: upload.data.byteLength, + }); + } + } + // [#32747] Every reserved id must still be its link's untouched row. + const reserved = reservedIdsOf(state); + for (const reservedId of reserved) { + if (!isOpenReservation(await store.getFile(reservedId), row.id, state.user_id)) refuseUnusableLink(); } // Spend the link: exactly one use turns it from open to used. @@ -984,16 +1215,17 @@ export class RecordFileAccess implements ICallerRecordFileService, UploadLinkDoo if (!spent) refuseUnusableLink(); // [#32686] The link row becomes the file: its id is the one the link answered. + // [#32747] The reserved rows become the later files, in order. const recordId = state.record_id; if (recordId === undefined) { - return await this.fileForNewRecordThroughLink(storage, store, row, state, upload, mimeType, writeContext); + return await this.filesForNewRecordThroughLink(storage, store, [row.id, ...reserved], state, typed, writeContext); } try { const outcome = state.target === 'attachments' - ? await this.attachThroughLink(state, recordId, user, upload, mimeType, organizationId) - : await this.fillFieldThroughLink(engine, storage, store, state, recordId, user, upload, mimeType, writeContext); + ? await this.attachThroughLink(state, recordId, user, typed[0], typed[0].mimeType, organizationId) + : await this.fillFieldThroughLink(engine, storage, store, state, recordId, user, typed, writeContext); return outcome; } finally { // The link row has done its work, used or refused: it holds no bytes, @@ -1017,46 +1249,60 @@ export class RecordFileAccess implements ICallerRecordFileService, UploadLinkDoo * (`pre-record-upload.ts`); the link's own secret digest goes with the old * metadata. A failed store discards the bytes and the row, so the id is * refused as unknown rather than ever reading as a file. + * + * [#32747] `fileIds[i]` takes `uploads[i]`: the link row the first, the + * reserved rows the rest, each with the same binding. A failure on any of + * them discards every one, the rows not reached yet included, so no id of + * the submit is left. */ - private async fileForNewRecordThroughLink( + private async filesForNewRecordThroughLink( storage: IStorageService, store: StorageMetadataStore, - row: FileRecord, + fileIds: string[], state: UploadLinkState, - upload: UploadLinkUpload, - mimeType: string, + uploads: TypedUpload[], writeContext: StorageWriteContext, - ): Promise { + ): Promise { const field = state.field as string; - const fileId = row.id; - const key = buildKey(FIELD_UPLOAD_SCOPE, fileId, upload.filename); - const size = upload.data.byteLength; + const claimUntil = new Date(this.now() + PRE_RECORD_CLAIM_WINDOW_SECONDS * 1000).toISOString(); + const keys = fileIds.map((fileId, i) => buildKey(FIELD_UPLOAD_SCOPE, fileId, uploads[i].filename)); + let stored = 0; try { - await storage.upload(key, upload.data, { contentType: mimeType }); - await store.updateFile( - fileId, - { - key, - name: upload.filename, - mime_type: mimeType, - size, - status: 'committed', - metadata: preRecordBindingMetadata({ - kind: PRE_RECORD_UPLOAD_KIND, - object: state.object, - field, - user_id: state.user_id, - ...(state.organization_id !== undefined ? { organization_id: state.organization_id } : {}), - claim_until: new Date(this.now() + PRE_RECORD_CLAIM_WINDOW_SECONDS * 1000).toISOString(), - }), - }, - writeContext, - ); + for (let i = 0; i < fileIds.length; i++) { + const upload = uploads[i]; + await storage.upload(keys[i], upload.data, { contentType: upload.mimeType }); + stored = i + 1; + await store.updateFile( + fileIds[i], + { + key: keys[i], + name: upload.filename, + mime_type: upload.mimeType, + size: upload.data.byteLength, + status: 'committed', + metadata: preRecordBindingMetadata({ + kind: PRE_RECORD_UPLOAD_KIND, + object: state.object, + field, + user_id: state.user_id, + ...(state.organization_id !== undefined ? { organization_id: state.organization_id } : {}), + claim_until: claimUntil, + }), + }, + writeContext, + ); + } } catch (err) { - await this.discard(storage, store, fileId, key, writeContext); + for (let i = 0; i < fileIds.length; i++) { + await this.discard(storage, store, fileIds[i], keys[i], writeContext, i < stored); + } throw err; } - return { object: state.object, fileId, size, field }; + return { + object: state.object, + field, + files: fileIds.map((fileId, i) => ({ fileId, size: uploads[i].data.byteLength })), + }; } private async attachThroughLink( @@ -1066,7 +1312,7 @@ export class RecordFileAccess implements ICallerRecordFileService, UploadLinkDoo upload: UploadLinkUpload, mimeType: string, organizationId: string | null, - ): Promise { + ): Promise { const attached = await this.deps.attachments.attachFileAs( { parentObject: state.object, @@ -1081,9 +1327,8 @@ export class RecordFileAccess implements ICallerRecordFileService, UploadLinkDoo return { object: state.object, recordId, - fileId: attached.fileId, - size: attached.size, attachmentId: attached.attachmentId, + files: [{ fileId: attached.fileId, size: attached.size }], }; } @@ -1094,6 +1339,10 @@ export class RecordFileAccess implements ICallerRecordFileService, UploadLinkDoo * and check the field's `accept` / `maxSize`) all judge it. A multi-file * field gains the file beside the ones it holds; a single-file field takes * it in place of the one it held, which the lifecycle releases. + * + * [#32747] A multi-file field gains every file of the submit in that one + * write. Any store or the write failing discards every file the submit + * stored, bytes and row, so the record holds what it held before. */ private async fillFieldThroughLink( engine: RecordFileEngine, @@ -1102,37 +1351,43 @@ export class RecordFileAccess implements ICallerRecordFileService, UploadLinkDoo state: UploadLinkState, recordId: string, user: ExecutionContext, - upload: UploadLinkUpload, - mimeType: string, + uploads: TypedUpload[], writeContext: StorageWriteContext, - ): Promise { + ): Promise { const field = state.field as string; const def = requireFileField(engine, state.object, field); - const fileId = randomUUID(); - const key = buildKey(FIELD_UPLOAD_SCOPE, fileId, upload.filename); - const size = upload.data.byteLength; - await store.createFile( - { - id: fileId, - key, - name: upload.filename, - mime_type: mimeType, - size, - scope: FIELD_UPLOAD_SCOPE, - acl: 'private', - status: 'pending', - owner_id: user.userId as string, - }, - writeContext, - ); + const files = uploads.map((upload) => { + const fileId = randomUUID(); + return { fileId, key: buildKey(FIELD_UPLOAD_SCOPE, fileId, upload.filename), upload, created: false, stored: false }; + }); try { - await storage.upload(key, upload.data, { contentType: mimeType }); - // A record write takes only a completed upload. - await store.updateFile(fileId, { status: 'committed' }, writeContext); - let value: string | string[] = fileId; + for (const file of files) { + const { upload } = file; + await store.createFile( + { + id: file.fileId, + key: file.key, + name: upload.filename, + mime_type: upload.mimeType, + size: upload.data.byteLength, + scope: FIELD_UPLOAD_SCOPE, + acl: 'private', + status: 'pending', + owner_id: user.userId as string, + }, + writeContext, + ); + file.created = true; + await storage.upload(file.key, upload.data, { contentType: upload.mimeType }); + file.stored = true; + // A record write takes only a completed upload. + await store.updateFile(file.fileId, { status: 'committed' }, writeContext); + } + const ids = files.map((file) => file.fileId); + let value: string | string[] = ids[0]; if (def.multiple === true) { const current = await this.readRecordAs(engine, state.object, recordId, user); - value = [...fileIdsIn(current[field]), fileId]; + value = [...fileIdsIn(current[field]), ...ids]; } // [#32734] Strict: a field the update would strip (`readonly`, or a // `readonlyWhen` that holds now) refuses the whole write rather than @@ -1149,23 +1404,35 @@ export class RecordFileAccess implements ICallerRecordFileService, UploadLinkDoo refuse('RECORD_NOT_FOUND', 404, `Record "${recordId}" not found in "${state.object}"`); } } catch (err) { - await this.discard(storage, store, fileId, key, writeContext); + for (const file of files) { + if (file.created) await this.discard(storage, store, file.fileId, file.key, writeContext, file.stored); + } readonlyRefusalOf(err, state.object, field); throw err; } - return { object: state.object, recordId, fileId, size, field }; + return { + object: state.object, + recordId, + field, + files: files.map((file) => ({ fileId: file.fileId, size: file.upload.data.byteLength })), + }; } - /** Undo a refused field upload: the bytes, then the row. Best-effort; the refusal is what is thrown. */ + /** + * Undo a refused field upload: the bytes, then the row. Best-effort; the + * refusal is what is thrown. [#32747] `bytesStored` false: the row is all + * there is to take back (its bytes never landed). + */ private async discard( storage: IStorageService, store: StorageMetadataStore, fileId: string, key: string, writeContext: StorageWriteContext, + bytesStored = true, ): Promise { try { - await storage.delete(key); + if (bytesStored) await storage.delete(key); } catch (err) { this.deps.logger.warn( `[storage] upload link: a refused upload could not delete its stored bytes (${(err as Error)?.message ?? err}). ` + diff --git a/packages/services/service-storage/src/storage-routes.ts b/packages/services/service-storage/src/storage-routes.ts index e1f86c0c63f..7928751cb88 100644 --- a/packages/services/service-storage/src/storage-routes.ts +++ b/packages/services/service-storage/src/storage-routes.ts @@ -65,8 +65,11 @@ import { buildKey } from './storage-key.js'; export { buildKey }; // [#30892] The upload-link doors: the service verbs they call, the one // refusal an unusable link gets, and the page a link opens. -import type { UploadLinkDoor, UploadLinkView } from './record-file-access.js'; +import type { UploadLinkDoor, UploadLinkUpload, UploadLinkView } from './record-file-access.js'; import { + UPLOAD_LINK_FORM_COUNT_FIELD, + UPLOAD_LINK_FORM_FILE_PREFIX, + UPLOAD_LINK_MAX_FILES, UPLOAD_LINK_SEGMENT, UPLOAD_LINK_UNUSABLE_CODE, UPLOAD_LINK_UNUSABLE_MESSAGE, @@ -1881,17 +1884,46 @@ export function registerStorageFamily( } // The declared length first, so an oversized body is refused before it // is read; the service judges the bytes read again, before the link is - // spent, so an oversized upload never uses it up. + // spent, so an oversized upload never uses it up. [#32747] A + // several-file submit (a form) may carry up to the link's cap of files, + // each within the limit; the service judges each file. const { maxUploadBytes } = currentLimits(); const declaredBody = declaredContentLength(req); + const several = isUploadLinkForm(req.headers?.['content-type']); + const formLimit = + several && maxUploadBytes !== undefined + ? maxUploadBytes * UPLOAD_LINK_MAX_FILES + UPLOAD_LINK_FORM_OVERHEAD_BYTES + : undefined; const tooLarge = declaredBody === undefined ? null - : uploadSizeRefusal(declaredBody, maxUploadBytes, (n) => `The upload body is ${n} bytes`); + : formLimit !== undefined + ? declaredBody > formLimit + ? `The upload body is ${declaredBody} bytes, over the ${formLimit} bytes a several-file upload can carry ` + + `(${UPLOAD_LINK_MAX_FILES} files, each within the "Max upload size (MB)" storage setting).` + : null + : uploadSizeRefusal(declaredBody, maxUploadBytes, (n) => `The upload body is ${n} bytes`); if (tooLarge !== null) { sendError(res, UPLOAD_TOO_LARGE_STATUS, UPLOAD_TOO_LARGE_CODE, tooLarge, { userMessage: copy.tooLarge }); return; } + if (several) { + const uploads = await uploadLinkFormFiles(req.body); + if (typeof uploads === 'string') { + sendError(res, 400, 'INVALID_REQUEST', uploads, { userMessage: copy.refused(uploads) }); + return; + } + const outcome = await door.consumeUploadLinkFiles(String(req.params.token ?? ''), uploads, caller.userId as string); + const fileIds = outcome.files.map((file) => file.fileId); + sendOk(res, { + fileId: fileIds[0], + fileIds, + files: outcome.files, + ...(outcome.field !== undefined ? { field: outcome.field } : {}), + ...(outcome.attachmentId !== undefined ? { attachmentId: outcome.attachmentId } : {}), + }); + return; + } let data: Buffer; if (req.rawBody) { data = await req.rawBody(); @@ -1913,6 +1945,8 @@ export function registerStorageFamily( ); sendOk(res, { fileId: outcome.fileId, + // [#32747] Every answer names its ids as a list, one here. + fileIds: [outcome.fileId], size: outcome.size, ...(outcome.field !== undefined ? { field: outcome.field } : {}), ...(outcome.attachmentId !== undefined ? { attachmentId: outcome.attachmentId } : {}), @@ -2412,6 +2446,70 @@ function relayUploadLinkRefusal(res: IHttpResponse, err: unknown, copy: UploadLi return true; } +/** + * [#32747] Room for a several-file submit's form framing (boundaries, part + * headers, the `count` field) beyond its files' own bytes, in the declared + * body cap. + */ +const UPLOAD_LINK_FORM_OVERHEAD_BYTES = 64 * 1024; + +/** [#32747] Is the submit a several-file form (`multipart/form-data`)? */ +function isUploadLinkForm(raw: string | string[] | undefined): boolean { + const first = Array.isArray(raw) ? raw[0] : raw; + return typeof first === 'string' && first.split(';')[0].trim().toLowerCase() === 'multipart/form-data'; +} + +/** [#32747] A form value that is a file: what a form parser hands for a file part. */ +interface FormFilePart { + name?: unknown; + type?: unknown; + arrayBuffer(): Promise; +} + +function isFormFilePart(value: unknown): value is FormFilePart { + return !!value && typeof value === 'object' && typeof (value as FormFilePart).arrayBuffer === 'function'; +} + +/** + * [#32747] The files of a several-file submit, in the order sent, or the + * reason the form is not one: `count` must name how many files it carries + * (a whole number), and parts `file0` … `fileN-1` must each be a file, with + * no other file part beside them, so a part a parser dropped (or one sent + * twice under one name, of which a parser keeps only the last) is refused + * rather than stored as fewer files than were picked. How many files the + * link takes is the service's to judge. + */ +async function uploadLinkFormFiles(body: unknown): Promise { + const form = body && typeof body === 'object' ? (body as Record) : {}; + const rawCount = form[UPLOAD_LINK_FORM_COUNT_FIELD]; + const countText = Array.isArray(rawCount) ? undefined : typeof rawCount === 'string' ? rawCount.trim() : undefined; + const count = countText !== undefined && /^[0-9]{1,3}$/.test(countText) ? Number(countText) : NaN; + if (!Number.isInteger(count) || count < 1) { + return ( + `A several-file upload is a form naming how many files it carries (${UPLOAD_LINK_FORM_COUNT_FIELD}) ` + + `and each file as ${UPLOAD_LINK_FORM_FILE_PREFIX}0, ${UPLOAD_LINK_FORM_FILE_PREFIX}1, …` + ); + } + const partName = new RegExp(`^${UPLOAD_LINK_FORM_FILE_PREFIX}(0|[1-9][0-9]*)$`); + const fileParts = Object.entries(form).filter(([key, value]) => isFormFilePart(value) || partName.test(key)); + if (fileParts.length !== count) { + return `The form names ${count} file(s) in ${UPLOAD_LINK_FORM_COUNT_FIELD} but carries ${fileParts.length}.`; + } + const uploads: UploadLinkUpload[] = []; + for (let i = 0; i < count; i++) { + const part = form[`${UPLOAD_LINK_FORM_FILE_PREFIX}${i}`]; + if (!isFormFilePart(part)) { + return `The form carries no file ${UPLOAD_LINK_FORM_FILE_PREFIX}${i}: the files are ${UPLOAD_LINK_FORM_FILE_PREFIX}0 … ${UPLOAD_LINK_FORM_FILE_PREFIX}${count - 1}.`; + } + uploads.push({ + filename: uploadLinkFilename(typeof part.name === 'string' ? part.name : undefined), + mimeType: uploadLinkMimeType(typeof part.type === 'string' ? part.type : undefined), + data: Buffer.from(await part.arrayBuffer()), + }); + } + return uploads; +} + /** The longest file name an upload link stores, in characters. */ const UPLOAD_LINK_FILENAME_MAX = 255; diff --git a/packages/services/service-storage/src/storage-routes.upload-link-refusal-relay.test.ts b/packages/services/service-storage/src/storage-routes.upload-link-refusal-relay.test.ts index 41d248f6ed2..31697ee3518 100644 --- a/packages/services/service-storage/src/storage-routes.upload-link-refusal-relay.test.ts +++ b/packages/services/service-storage/src/storage-routes.upload-link-refusal-relay.test.ts @@ -54,6 +54,7 @@ function doorsThrowing(thrown: unknown) { const door: UploadLinkDoor = { inspectUploadLink: async () => { throw thrown; }, consumeUploadLink: async () => { throw thrown; }, + consumeUploadLinkFiles: async () => { throw thrown; }, }; registerStorageFamily( http as any, diff --git a/packages/services/service-storage/src/storage-service-plugin.ts b/packages/services/service-storage/src/storage-service-plugin.ts index dd9101c8833..a4f859db267 100644 --- a/packages/services/service-storage/src/storage-service-plugin.ts +++ b/packages/services/service-storage/src/storage-service-plugin.ts @@ -1378,7 +1378,10 @@ function resolveUploadLinkDoor(registry: StorageGateRegistry): () => UploadLinkD } catch { return undefined; } - return service && typeof service.inspectUploadLink === 'function' && typeof service.consumeUploadLink === 'function' + return service && + typeof service.inspectUploadLink === 'function' && + typeof service.consumeUploadLink === 'function' && + typeof service.consumeUploadLinkFiles === 'function' ? (service as UploadLinkDoor) : undefined; }; diff --git a/packages/services/service-storage/src/upload-link-wire.ts b/packages/services/service-storage/src/upload-link-wire.ts index 21d28a66f33..b4fa158166b 100644 --- a/packages/services/service-storage/src/upload-link-wire.ts +++ b/packages/services/service-storage/src/upload-link-wire.ts @@ -24,3 +24,29 @@ export const UPLOAD_LINK_UNUSABLE_STATUS = 404; export const UPLOAD_LINK_UNUSABLE_CODE: StandardErrorCode = 'RESOURCE_NOT_FOUND'; export const UPLOAD_LINK_UNUSABLE_MESSAGE = 'This upload link cannot be used: it was used already, it has expired, it was made for someone else, or it does not exist. Ask for a new link.'; + +/** + * [#32747] The most files one upload link takes in its one submit (ruling A: + * one link, several files, capped). Only a link for a file field declared + * `multiple: true` takes more than one; a single-file field link and an + * attachments link take one. File fields declare no item cap of their own, so + * this is the platform's. A submit carrying more is refused before the link is + * spent: 400 `VALIDATION_ERROR` ({@link UPLOAD_LINK_FILE_COUNT_CODE}). + */ +export const UPLOAD_LINK_MAX_FILES = 10; + +/** [#32747] The refusal of a submit carrying a number of files the link does not take. */ +export const UPLOAD_LINK_FILE_COUNT_STATUS = 400; +export const UPLOAD_LINK_FILE_COUNT_CODE: StandardErrorCode = 'VALIDATION_ERROR'; + +/** + * [#32747] The multipart form a several-file submit is sent as: one part per + * file named `file0` … `fileN-1`, in the order picked, and a `count` field + * naming N. Indexed names, because a form parser that keeps one value per + * name (Hono's `parseBody`, both transports) keeps only the last of a + * repeated one; `count` lets the door refuse a body that lost a part rather + * than store fewer files than were sent. Each part's file name is + * URI-encoded, as the single-file submit's `x-file-name` header is. + */ +export const UPLOAD_LINK_FORM_COUNT_FIELD = 'count'; +export const UPLOAD_LINK_FORM_FILE_PREFIX = 'file'; From e73acef0706d4518fba944a807b1a3067baecc0b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 20:07:05 +0000 Subject: [PATCH 02/10] wip(storage): several-file upload page, copy and pins Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibzVFJSNs6XZjC8jkNJ --- .../record-file-access.integration.test.ts | 271 +++++++++++++++++- .../src/upload-link-copy.test.ts | 11 + .../service-storage/src/upload-link-copy.ts | 100 +++++++ .../service-storage/src/upload-link-page.ts | 45 ++- 4 files changed, 416 insertions(+), 11 deletions(-) diff --git a/packages/services/service-storage/src/record-file-access.integration.test.ts b/packages/services/service-storage/src/record-file-access.integration.test.ts index 276dad4e0ac..760f977e34d 100644 --- a/packages/services/service-storage/src/record-file-access.integration.test.ts +++ b/packages/services/service-storage/src/record-file-access.integration.test.ts @@ -41,6 +41,13 @@ * console-style upload and save is taken as before. The create verdict is a * `security` service stood in for the span of the case that asks it. * + * #32747 — one link, several files (ruling A): a link for a multi-file field + * takes up to the cap in one submit, a form of `file0` … `fileN-1` and + * `count`; every file is judged before the link is spent, and the submit + * lands all or nothing. A link that names no record answers every id when it + * is minted, reserving the later ones as rows no write takes before the + * upload. A single-file field link and an attachments link still take one. + * * #32712 — the page, and the refusals it shows, in the request's language: * `Accept-Language`, else the workspace default, else English. The workspace * default is the fixture's `settings` service, answering the `localization` @@ -65,7 +72,7 @@ import { installDefaultOrganization, DEFAULT_ORGANIZATION_ID } from './default-o import { UPLOAD_LINK_TTL_SECONDS } from './record-file-access.js'; import { PRE_RECORD_CLAIM_WINDOW_SECONDS } from './pre-record-upload.js'; import { resolveThrownHttpError } from '@objectstack/types'; -import { UPLOAD_LINK_UNUSABLE_MESSAGE } from './upload-link-wire.js'; +import { UPLOAD_LINK_MAX_FILES, UPLOAD_LINK_UNUSABLE_MESSAGE } from './upload-link-wire.js'; import { UPLOAD_LINK_COPY } from './upload-link-copy.js'; const BASE = '/api/v1/storage'; @@ -217,6 +224,8 @@ describe('#30892 — a record\'s files for a resolved caller: read one, attach o status: { name: 'status', type: 'text' }, invoices: { name: 'invoices', label: 'Invoices', type: 'file', multiple: true, readonlyWhen: "record.status == 'approved'" }, stamp: { name: 'stamp', label: 'Stamp', type: 'file', readonly: true }, + // [#32747] A multi-file field that takes only PDFs: invoices for one claim. + scans: { name: 'scans', label: 'Scans', type: 'file', multiple: true, accept: ['application/pdf', '.pdf'] }, }, }, { // [#32686] The measured case: an expense line whose e-invoice is required. @@ -475,7 +484,10 @@ describe('#30892 — a record\'s files for a resolved caller: read one, attach o 'x-object': 'claim', 'x-record-id': ids.claimA, 'x-field': 'photos', 'x-user-id': OUTSIDER.userId, }); expect(res._status, JSON.stringify(res._json)).toBe(200); - expect(res._json).toEqual({ success: true, data: { fileId: expect.any(String), size: 11, field: 'policy' } }); + expect(res._json).toEqual({ + success: true, + data: { fileId: expect.any(String), fileIds: [expect.any(String)], size: 11, field: 'policy' }, + }); const fileId = res._json.data.fileId as string; expect((await claim(ids.claimB)).policy).toBe(fileId); expect((await claim(ids.claimA)).policy).not.toBe(fileId); @@ -988,7 +1000,7 @@ describe('#30892 — a record\'s files for a resolved caller: read one, attach o // The browser upload: the bytes land under the id the link answered, on no record. const res = await useLink(tokenOf(grant.path), Buffer.from('%PDF-1.4 taxi receipt')); expect(res._status, JSON.stringify(res._json)).toBe(200); - expect(res._json).toEqual({ success: true, data: { fileId, size: 21, field: 'invoice' } }); + expect(res._json).toEqual({ success: true, data: { fileId, fileIds: [fileId], size: 21, field: 'invoice' } }); const landed = await fileRow(fileId); expect(landed).toMatchObject({ status: 'committed', owner_id: OWNER.userId, size: 21, name: 'scan 1.pdf', mime_type: 'application/pdf', @@ -1179,4 +1191,257 @@ describe('#30892 — a record\'s files for a resolved caller: read one, attach o expect(small._status, JSON.stringify(small._json)).toBe(200); }); }); + + describe('#32747 — one link, several files: a multi-file field takes them in one submit, all or nothing', () => { + type Pick = { name: string; bytes: Buffer; type?: string }; + const pdf = (name: string, text = `%PDF-1.4 ${name}`): Pick => ({ name, bytes: Buffer.from(text), type: 'application/pdf' }); + /** The page's several-file submit: one form, `count` and `file0` … `fileN-1`, each name URI-encoded. */ + const useLinkForm = (token: string, picks: Pick[], user: string | null = OWNER.userId, extra: Record = {}) => { + const body: Record = { count: String(picks.length), ...extra }; + picks.forEach((pick, i) => { + body[`file${i}`] = new File([pick.bytes], encodeURIComponent(pick.name), { type: pick.type ?? 'application/pdf' }); + }); + return call('PUT', `${BASE}/upload-links/:token`, { + params: { token }, + headers: { 'content-type': 'multipart/form-data; boundary=----os', ...sessionOf(user) }, + body, + }); + }; + const failureOf = (write: Promise) => write.then(() => null, (e: unknown) => resolveThrownHttpError(e)); + /** The `sys_file` rows named one of `names`: a submit's files, by the unique names a case picks. */ + const rowsNamed = async (names: string[]) => + ((await engine.find('sys_file', { where: { name: { $in: names } }, context: SYS } as never)) as Array>); + const newClaim = async (name: string) => + String((await engine.insert('claim', { name, owner: OWNER.userId, organization_id: ORG }, { context: SYS } as never)).id); + + it('a record link: three PDFs in one submit land as three files on the field, in one write, as the minting user\'s', async () => { + const id = await newClaim('three'); + const kept = await uploadThroughLink({ field: 'scans' }, Buffer.from('%PDF-1.4 kept'), id); + const grant = await files.createUploadLinkAs('claim', id, { field: 'scans' }, OWNER as never); + const res = await useLinkForm(tokenOf(grant.path), [pdf('inv-1.pdf'), pdf('inv-2.pdf'), pdf('inv-3.pdf')]); + expect(res._status, JSON.stringify(res._json)).toBe(200); + const fileIds = res._json.data.fileIds as string[]; + expect(fileIds).toHaveLength(3); + expect(res._json.data).toEqual({ + fileId: fileIds[0], + fileIds, + files: fileIds.map((fileId) => ({ fileId, size: 18 })), + field: 'scans', + }); + expect((await claim(id)).scans).toEqual([kept.fileId, ...fileIds]); + for (const [i, fileId] of fileIds.entries()) { + expect(await fileRow(fileId)).toMatchObject({ + status: 'committed', owner_id: OWNER.userId, name: `inv-${i + 1}.pdf`, mime_type: 'application/pdf', size: 18, + ref_object: 'claim', ref_id: id, ref_field: 'scans', + }); + } + // One submit spent it: the next use is the one unusable-link answer. + const again = await useLinkForm(tokenOf(grant.path), [pdf('inv-4.pdf')]); + expect(again._status).toBe(404); + expect(again._json.error.code).toBe('RESOURCE_NOT_FOUND'); + }); + + it('a link that names no record: count 3 answers three ids, the submit fills them, and the create takes all three', async () => { + const grant = await files.createUploadLinkForNewRecordAs('claim', { field: 'scans', count: 3 }, OWNER as never); + expect(grant.fileIds).toHaveLength(3); + expect(grant.fileIds[0]).toBe(grant.token.split('.')[0]); + for (const reserved of grant.fileIds.slice(1)) { + // A row that holds nothing, owned by the minting user: the pending-upload retention reaps it. + expect(await fileRow(reserved)).toMatchObject({ status: 'pending', owner_id: OWNER.userId, name: 'upload-link (reserved)', size: 0 }); + } + const res = await useLinkForm(tokenOf(grant.path), [pdf('pre-1.pdf'), pdf('pre-2.pdf'), pdf('pre-3.pdf')]); + expect(res._status, JSON.stringify(res._json)).toBe(200); + expect(res._json.data.fileIds).toEqual(grant.fileIds); + for (const [i, fileId] of grant.fileIds.entries()) { + const row = await fileRow(fileId); + expect(row).toMatchObject({ status: 'committed', owner_id: OWNER.userId, name: `pre-${i + 1}.pdf`, ref_id: null }); + expect(JSON.parse(row.metadata)).toMatchObject({ kind: 'pre_record_upload', object: 'claim', field: 'scans', user_id: OWNER.userId }); + } + // Each id is claimable only by that user, into that field. + expect(await failureOf(engine.insert('claim', { name: 'R', owner: REVIEWER.userId, scans: [grant.fileIds[1]] }, { context: REVIEWER } as never))) + .toMatchObject({ status: 400, code: 'VALIDATION_FAILED' }); + const created = await engine.insert('claim', { name: 'C', owner: OWNER.userId, scans: grant.fileIds }, { context: OWNER } as never); + expect((await claim(String(created.id))).scans).toEqual(grant.fileIds); + for (const fileId of grant.fileIds) { + expect(await fileRow(fileId)).toMatchObject({ ref_object: 'claim', ref_id: String(created.id), ref_field: 'scans' }); + } + }); + + it('before its upload, a reserved id is refused to every write, the uploader\'s own included, and nothing serves it', async () => { + const grant = await files.createUploadLinkForNewRecordAs('claim', { field: 'scans', count: 2 }, OWNER as never); + const reserved = grant.fileIds[1]; + // The uploader: an upload that never completed (the incomplete-upload arm). + expect(await failureOf(engine.insert('claim', { name: 'O', owner: OWNER.userId, scans: [reserved] }, { context: OWNER } as never))) + .toMatchObject({ + status: 400, + code: 'VALIDATION_FAILED', + details: { fields: [{ field: 'scans', code: 'invalid_value', message: `Scans cannot reference file ${reserved}: its upload was never completed. Complete the upload, then save again.` }] }, + }); + // Another user and a system write: a file they cannot open (the not-yours arm). + const unreadable = 'Scans cannot reference this file: it is not a file you can open. Choose a file you can open, or upload it again.'; + for (const who of [REVIEWER, SYS]) { + expect(await failureOf(engine.insert('claim', { name: 'X', owner: OWNER.userId, scans: [reserved] }, { context: who } as never))) + .toMatchObject({ status: 400, code: 'VALIDATION_FAILED', details: { fields: [{ field: 'scans', message: unreadable }] } }); + } + // The download door serves no pending row, to its owner either. + const url = await call('GET', `${BASE}/files/:fileId/url`, { params: { fileId: reserved }, headers: sessionOf(OWNER.userId) }); + expect(url._status, JSON.stringify(url._json)).toBe(404); + expect(url._json.error.code).toBe('FILE_NOT_FOUND'); + // It is no link: its own id with any secret is the one unusable-link answer. + const asLink = await useLinkForm(`${reserved}.${grant.token.split('.')[1]}`, [pdf('x.pdf')]); + expect(asLink._status).toBe(404); + expect(await fileRow(reserved)).toMatchObject({ status: 'pending', name: 'upload-link (reserved)', ref_id: null }); + }); + + it('the cap: more than ten files is refused 400 VALIDATION_ERROR before the spend; nothing is stored and the link still takes ten', async () => { + const id = await newClaim('cap'); + const grant = await files.createUploadLinkAs('claim', id, { field: 'scans' }, OWNER as never); + const eleven = Array.from({ length: UPLOAD_LINK_MAX_FILES + 1 }, (_, i) => pdf(`cap-${i}.pdf`)); + const refused = await useLinkForm(tokenOf(grant.path), eleven); + expect(refused._status, JSON.stringify(refused._json)).toBe(400); + expect(refused._json.error.code).toBe('VALIDATION_ERROR'); + expect(refused._json.error.message).toContain(`takes up to ${UPLOAD_LINK_MAX_FILES} files`); + expect(await rowsNamed(eleven.map((p) => p.name))).toEqual([]); + expect((await claim(id)).scans ?? null).toBeNull(); + const ten = await useLinkForm(tokenOf(grant.path), eleven.slice(0, UPLOAD_LINK_MAX_FILES)); + expect(ten._status, JSON.stringify(ten._json)).toBe(200); + expect((await claim(id)).scans).toHaveLength(UPLOAD_LINK_MAX_FILES); + }); + + it('a link that names no record takes exactly its count: two of three is refused before the spend, three land', async () => { + const grant = await files.createUploadLinkForNewRecordAs('claim', { field: 'scans', count: 3 }, OWNER as never); + const short = await useLinkForm(tokenOf(grant.path), [pdf('ex-1.pdf'), pdf('ex-2.pdf')]); + expect(short._status, JSON.stringify(short._json)).toBe(400); + expect(short._json.error).toMatchObject({ code: 'VALIDATION_ERROR' }); + expect(short._json.error.message).toContain('takes exactly 3 files'); + expect(await fileRow(grant.fileIds[0])).toMatchObject({ status: 'pending', name: 'upload-link' }); + const full = await useLinkForm(tokenOf(grant.path), [pdf('ex-1.pdf'), pdf('ex-2.pdf'), pdf('ex-3.pdf')]); + expect(full._status, JSON.stringify(full._json)).toBe(200); + }); + + it('control: a single-file field link and an attachments link still take one file; a second is refused, and the one lands', async () => { + for (const target of [{ field: 'policy' }, { attachments: true as const }]) { + const grant = await files.createUploadLinkAs('claim', ids.claimB, target, OWNER as never); + const two = await useLinkForm(tokenOf(grant.path), [pdf('one-a.pdf'), pdf('one-b.pdf')]); + expect(two._status, JSON.stringify(two._json)).toBe(400); + expect(two._json.error.code).toBe('VALIDATION_ERROR'); + expect(two._json.error.message).toContain('takes one file'); + expect(await rowsNamed(['one-a.pdf', 'one-b.pdf'])).toEqual([]); + const one = await useLink(tokenOf(grant.path), Buffer.from('%PDF-1.4 one')); + expect(one._status, JSON.stringify(one._json)).toBe(200); + // And once used, a second file through it is the one unusable-link answer, as before. + const second = await useLink(tokenOf(grant.path), Buffer.from('%PDF-1.4 two')); + expect(second._status).toBe(404); + } + // A link naming no record for a single-file field: count above one is refused when minted. + expect(await refusalOf(files.createUploadLinkForNewRecordAs('claim', { field: 'policy', count: 2 }, OWNER as never))) + .toMatchObject({ code: 'VALIDATION_ERROR', status: 400 }); + for (const count of [0, UPLOAD_LINK_MAX_FILES + 1, 1.5]) { + expect(await refusalOf(files.createUploadLinkForNewRecordAs('claim', { field: 'scans', count }, OWNER as never))) + .toMatchObject({ code: 'VALIDATION_ERROR', status: 400 }); + } + }); + + it('another signed-in user cannot use a several-file link: the one 404, nothing spent, and the minting user then uses it', async () => { + const id = await newClaim('stranger'); + const grant = await files.createUploadLinkAs('claim', id, { field: 'scans' }, OWNER as never); + const stranger = await useLinkForm(tokenOf(grant.path), [pdf('st-1.pdf'), pdf('st-2.pdf')], REVIEWER.userId); + expect(stranger._status).toBe(404); + expect(stranger._json.error.code).toBe('RESOURCE_NOT_FOUND'); + expect(await rowsNamed(['st-1.pdf', 'st-2.pdf'])).toEqual([]); + const owner = await useLinkForm(tokenOf(grant.path), [pdf('st-1.pdf'), pdf('st-2.pdf')]); + expect(owner._status, JSON.stringify(owner._json)).toBe(200); + }); + + it('file 2 of 3 the field does not take: the whole submit is refused before the spend, the record unchanged, nothing stored', async () => { + const id = await newClaim('accept'); + const grant = await files.createUploadLinkAs('claim', id, { field: 'scans' }, OWNER as never); + const picks = [pdf('acc-1.pdf'), { name: 'acc-2.png', bytes: Buffer.from('png'), type: 'image/png' }, pdf('acc-3.pdf')]; + const refused = await useLinkForm(tokenOf(grant.path), picks); + expect(refused._status, JSON.stringify(refused._json)).toBe(400); + expect(refused._json.error.code).toBe('ERR_FILE_CONSTRAINT'); + expect((await claim(id)).scans ?? null).toBeNull(); + expect(await rowsNamed(picks.map((p) => p.name))).toEqual([]); + // Not spent: the same link takes the three PDFs. + const ok = await useLinkForm(tokenOf(grant.path), [pdf('acc-1.pdf'), pdf('acc-2.pdf'), pdf('acc-3.pdf')]); + expect(ok._status, JSON.stringify(ok._json)).toBe(200); + }); + + it('file 2 of 3 failing in the storage write after the spend: the record is unchanged and no row or bytes of the submit are left', async () => { + const id = await newClaim('store-fail'); + const kept = await uploadThroughLink({ field: 'scans' }, Buffer.from('%PDF-1.4 kept'), id); + const grant = await files.createUploadLinkAs('claim', id, { field: 'scans' }, OWNER as never); + const upload = storage.upload.bind(storage); + const keys: string[] = []; + let calls = 0; + vi.spyOn(storage, 'upload').mockImplementation(async (key: string, data: Buffer, opts?: any) => { + calls += 1; + if (calls === 2) throw new Error('disk full'); + keys.push(key); + return upload(key, data, opts); + }); + const picks = [pdf('sf-1.pdf'), pdf('sf-2.pdf'), pdf('sf-3.pdf')]; + const res = await useLinkForm(tokenOf(grant.path), picks); + expect(res._status).toBe(500); + expect((await claim(id)).scans).toEqual([kept.fileId]); + expect(await rowsNamed(picks.map((p) => p.name))).toEqual([]); + expect(keys).toHaveLength(1); + expect(await storage.exists(keys[0])).toBe(false); + vi.restoreAllMocks(); + // A link naming no record: every id of the submit is gone, the reserved ones not reached included. + const pre = await files.createUploadLinkForNewRecordAs('claim', { field: 'scans', count: 3 }, OWNER as never); + calls = 0; + keys.length = 0; + vi.spyOn(storage, 'upload').mockImplementation(async (key: string, data: Buffer, opts?: any) => { + calls += 1; + if (calls === 2) throw new Error('disk full'); + keys.push(key); + return upload(key, data, opts); + }); + const preRes = await useLinkForm(tokenOf(pre.path), [pdf('spf-1.pdf'), pdf('spf-2.pdf'), pdf('spf-3.pdf')]); + expect(preRes._status).toBe(500); + for (const fileId of pre.fileIds) expect(await fileRow(fileId)).toBeUndefined(); + expect(await storage.exists(keys[0])).toBe(false); + }); + + it('the record\'s write refusing after the spend (a lock): 409, the record unchanged, none of the files kept', async () => { + const id = await newClaim('lock-after'); + const grant = await files.createUploadLinkAs('claim', id, { field: 'scans' }, OWNER as never); + locked.add(id); + try { + const picks = [pdf('lk-1.pdf'), pdf('lk-2.pdf'), pdf('lk-3.pdf')]; + const res = await useLinkForm(tokenOf(grant.path), picks); + expect(res._status, JSON.stringify(res._json)).toBe(409); + expect(res._json.error.code).toBe('RECORD_LOCKED'); + expect((await claim(id)).scans ?? null).toBeNull(); + expect(await rowsNamed(picks.map((p) => p.name))).toEqual([]); + } finally { + locked.delete(id); + } + }); + + it('a form that lost a part is refused 400 INVALID_REQUEST and spends nothing', async () => { + const id = await newClaim('lost-part'); + const grant = await files.createUploadLinkAs('claim', id, { field: 'scans' }, OWNER as never); + const lost = await useLinkForm(tokenOf(grant.path), [pdf('lp-1.pdf'), pdf('lp-2.pdf')], OWNER.userId, { count: '3' }); + expect(lost._status, JSON.stringify(lost._json)).toBe(400); + expect(lost._json.error.code).toBe('INVALID_REQUEST'); + const ok = await useLinkForm(tokenOf(grant.path), [pdf('lp-1.pdf'), pdf('lp-2.pdf')]); + expect(ok._status, JSON.stringify(ok._json)).toBe(200); + }); + + it('the page: a multi-file field link picks several, a link naming no record asks for its count, a single-file link picks one', async () => { + const id = await newClaim('page'); + const several = await openLink(tokenOf((await files.createUploadLinkAs('claim', id, { field: 'scans' }, OWNER as never)).path)); + expect(several._status).toBe(200); + expect(String(several._sent)).toContain(''); + expect(String(several._sent)).toContain(UPLOAD_LINK_COPY.en.wantedSeveral(UPLOAD_LINK_MAX_FILES)); + const exact = await openLink(tokenOf((await files.createUploadLinkForNewRecordAs('claim', { field: 'scans', count: 3 }, OWNER as never)).path)); + expect(String(exact._sent)).toContain(UPLOAD_LINK_COPY.en.wantedExactly(3)); + expect(String(exact._sent)).toContain('multiple'); + const single = await openLink(tokenOf((await files.createUploadLinkAs('claim', id, { field: 'policy' }, OWNER as never)).path)); + expect(String(single._sent)).toContain(''); + expect(String(single._sent)).not.toContain('multiple'); + }); + }); }); diff --git a/packages/services/service-storage/src/upload-link-copy.test.ts b/packages/services/service-storage/src/upload-link-copy.test.ts index fe9a618d97f..a3e1e12dc0b 100644 --- a/packages/services/service-storage/src/upload-link-copy.test.ts +++ b/packages/services/service-storage/src/upload-link-copy.test.ts @@ -31,6 +31,13 @@ function sentencesOf(copy: UploadLinkCopy): Record { out.expires = copy.expires('UNTIL'); } else if (key === 'refused') { out.refused = copy.refused('REASON'); + } else if (key === 'wantedSeveral') { + out.wantedSeveral = copy.wantedSeveral(7); + } else if (key === 'wantedExactly') { + out.wantedExactly = copy.wantedExactly(7); + } else if (key === 'pickCount') { + out['pickCount(exact)'] = copy.pickCount(7, 7); + out['pickCount(up to)'] = copy.pickCount(1, 7); } else { out[key] = value as string; } @@ -49,6 +56,10 @@ describe('#32712 — the upload-link page\'s sentences', () => { for (const [name, text] of Object.entries(sentences)) expect(text.trim(), `${tag} ${name}`).not.toBe(''); expect(sentences.expires, tag).toContain('UNTIL'); expect(sentences.refused, tag).toContain('REASON'); + // [#32747] The several-file lines say how many. + for (const name of ['wantedSeveral', 'wantedExactly', 'pickCount(exact)', 'pickCount(up to)']) { + expect(sentences[name], `${tag} ${name}`).toContain('7'); + } } }); diff --git a/packages/services/service-storage/src/upload-link-copy.ts b/packages/services/service-storage/src/upload-link-copy.ts index c748e8f4f8e..bbfa1227609 100644 --- a/packages/services/service-storage/src/upload-link-copy.ts +++ b/packages/services/service-storage/src/upload-link-copy.ts @@ -73,6 +73,19 @@ export interface UploadLinkCopy extends UploadLinkRefusalCopy { * waits for the record the assistant creates, so nothing was attached yet. */ received: string; + /** + * [#32747] What is asked for, on a link to a multi-file field: up to `max` + * files for a record, or exactly `n` for a record not yet created. + */ + wantedSeveral(max: number): string; + wantedExactly(n: number): string; + /** [#32747] The picker's label when it takes several files. */ + filesLabel: string; + /** [#32747] Done, for a submit that carried several files. */ + attachedSeveral: string; + receivedSeveral: string; + /** [#32747] The page's own line when the files picked are not as many as the link takes. */ + pickCount(min: number, max: number): string; /** The upload failed and the answer carried no sentence to show. */ failed: string; connectionLost: string; @@ -97,6 +110,14 @@ export const UPLOAD_LINK_COPY: Record = { uploading: 'Uploading…', attached: 'Done. The file was attached; you can close this page.', received: 'Done. The file was received; go back to the assistant to finish.', + wantedSeveral: (max) => + `Files were asked for, to be put in a file field of a record. Pick up to ${max} and send them together.`, + wantedExactly: (n) => + `${n} files were asked for, to be put in a file field of a record. Pick all ${n} and send them together.`, + filesLabel: 'Files', + attachedSeveral: 'Done. The files were attached; you can close this page.', + receivedSeveral: 'Done. The files were received; go back to the assistant to finish.', + pickCount: (min, max) => (min === max ? `Pick exactly ${min} files.` : `Pick at most ${max} files.`), failed: 'The upload failed.', connectionLost: 'The upload failed: the connection was lost. Ask for a new link if this one no longer works.', unusableTitle: 'Upload link', @@ -129,6 +150,12 @@ export const UPLOAD_LINK_COPY: Record = { uploading: '正在上传…', attached: '完成,文件已添加。你可以关闭此页面。', received: '完成,文件已收到。请回到助手那里完成后续操作。', + wantedSeveral: (max) => `有人请你提供一些文件,它们将放入一条记录的文件字段中。最多可选择 ${max} 个,一起发送。`, + wantedExactly: (n) => `有人请你提供 ${n} 个文件,它们将放入一条记录的文件字段中。请选择全部 ${n} 个,一起发送。`, + filesLabel: '文件', + attachedSeveral: '完成,文件已全部添加。你可以关闭此页面。', + receivedSeveral: '完成,文件已全部收到。请回到助手那里完成后续操作。', + pickCount: (min, max) => (min === max ? `请恰好选择 ${min} 个文件。` : `最多选择 ${max} 个文件。`), failed: '上传失败。', connectionLost: '上传失败:连接已中断。如果此链接已无法使用,请索取新的链接。', unusableTitle: '上传链接', @@ -159,6 +186,12 @@ export const UPLOAD_LINK_COPY: Record = { uploading: '正在上傳…', attached: '完成,檔案已新增。你可以關閉此頁面。', received: '完成,檔案已收到。請回到助理那裡完成後續操作。', + wantedSeveral: (max) => `有人請你提供一些檔案,它們將放入一筆記錄的檔案欄位中。最多可選擇 ${max} 個,一起傳送。`, + wantedExactly: (n) => `有人請你提供 ${n} 個檔案,它們將放入一筆記錄的檔案欄位中。請選擇全部 ${n} 個,一起傳送。`, + filesLabel: '檔案', + attachedSeveral: '完成,檔案已全部新增。你可以關閉此頁面。', + receivedSeveral: '完成,檔案已全部收到。請回到助理那裡完成後續操作。', + pickCount: (min, max) => (min === max ? `請剛好選擇 ${min} 個檔案。` : `最多選擇 ${max} 個檔案。`), failed: '上傳失敗。', connectionLost: '上傳失敗:連線已中斷。如果此連結已無法使用,請索取新的連結。', unusableTitle: '上傳連結', @@ -189,6 +222,15 @@ export const UPLOAD_LINK_COPY: Record = { uploading: 'アップロード中…', attached: '完了しました。ファイルが追加されました。このページは閉じてかまいません。', received: '完了しました。ファイルを受け取りました。アシスタントに戻って続きを進めてください。', + wantedSeveral: (max) => + `レコードのファイル項目に入れるファイルが求められています。最大 ${max} 個まで選んで、まとめて送信してください。`, + wantedExactly: (n) => + `レコードのファイル項目に入れるファイルが ${n} 個求められています。${n} 個すべてを選んで、まとめて送信してください。`, + filesLabel: 'ファイル', + attachedSeveral: '完了しました。ファイルがすべて追加されました。このページは閉じてかまいません。', + receivedSeveral: '完了しました。ファイルをすべて受け取りました。アシスタントに戻って続きを進めてください。', + pickCount: (min, max) => + min === max ? `ちょうど ${min} 個のファイルを選んでください。` : `ファイルは最大 ${max} 個まで選べます。`, failed: 'アップロードに失敗しました。', connectionLost: 'アップロードに失敗しました: 接続が切れました。このリンクが使えなくなった場合は、新しいリンクを依頼してください。', unusableTitle: 'アップロードリンク', @@ -219,6 +261,15 @@ export const UPLOAD_LINK_COPY: Record = { uploading: '업로드 중…', attached: '완료되었습니다. 파일이 추가되었으니 이 페이지를 닫아도 됩니다.', received: '완료되었습니다. 파일을 받았습니다. 어시스턴트로 돌아가 마무리하세요.', + wantedSeveral: (max) => + `레코드의 파일 필드에 넣을 파일들이 요청되었습니다. 최대 ${max}개까지 선택해 한 번에 보내 주세요.`, + wantedExactly: (n) => + `레코드의 파일 필드에 넣을 파일 ${n}개가 요청되었습니다. ${n}개를 모두 선택해 한 번에 보내 주세요.`, + filesLabel: '파일', + attachedSeveral: '완료되었습니다. 파일이 모두 추가되었으니 이 페이지를 닫아도 됩니다.', + receivedSeveral: '완료되었습니다. 파일을 모두 받았습니다. 어시스턴트로 돌아가 마무리하세요.', + pickCount: (min, max) => + min === max ? `파일을 정확히 ${min}개 선택하세요.` : `파일은 최대 ${max}개까지 선택할 수 있습니다.`, failed: '업로드에 실패했습니다.', connectionLost: '업로드에 실패했습니다: 연결이 끊어졌습니다. 이 링크가 더 이상 작동하지 않으면 새 링크를 요청하세요.', unusableTitle: '업로드 링크', @@ -249,6 +300,14 @@ export const UPLOAD_LINK_COPY: Record = { uploading: 'Subiendo…', attached: 'Listo. El archivo se ha adjuntado; puedes cerrar esta página.', received: 'Listo. Se ha recibido el archivo; vuelve al asistente para terminar.', + wantedSeveral: (max) => + `Se han pedido archivos para ponerlos en un campo de archivo de un registro. Elige hasta ${max} y envíalos juntos.`, + wantedExactly: (n) => + `Se han pedido ${n} archivos para ponerlos en un campo de archivo de un registro. Elige los ${n} y envíalos juntos.`, + filesLabel: 'Archivos', + attachedSeveral: 'Listo. Los archivos se han adjuntado; puedes cerrar esta página.', + receivedSeveral: 'Listo. Se han recibido los archivos; vuelve al asistente para terminar.', + pickCount: (min, max) => (min === max ? `Elige exactamente ${min} archivos.` : `Elige como máximo ${max} archivos.`), failed: 'La subida ha fallado.', connectionLost: 'La subida ha fallado: se ha perdido la conexión. Pide un enlace nuevo si este ya no funciona.', unusableTitle: 'Enlace de subida', @@ -279,6 +338,12 @@ export const UPLOAD_LINK_COPY: Record = { uploading: 'جارٍ الرفع…', attached: 'تم. أُرفق الملف؛ يمكنك إغلاق هذه الصفحة.', received: 'تم. استُلم الملف؛ عد إلى المساعد لإكمال العملية.', + wantedSeveral: (max) => `طُلبت ملفات لوضعها في حقل ملف ضمن سجل. اختر حتى ${max} ملفات وأرسلها معًا.`, + wantedExactly: (n) => `طُلب ${n} ملفات لوضعها في حقل ملف ضمن سجل. اختر الملفات الـ ${n} كلها وأرسلها معًا.`, + filesLabel: 'الملفات', + attachedSeveral: 'تم. أُرفقت الملفات؛ يمكنك إغلاق هذه الصفحة.', + receivedSeveral: 'تم. استُلمت الملفات؛ عد إلى المساعد لإكمال العملية.', + pickCount: (min, max) => (min === max ? `اختر ${min} ملفات بالضبط.` : `اختر ${max} ملفات على الأكثر.`), failed: 'فشل الرفع.', connectionLost: 'فشل الرفع: انقطع الاتصال. اطلب رابطًا جديدًا إذا لم يعد هذا الرابط يعمل.', unusableTitle: 'رابط الرفع', @@ -309,6 +374,15 @@ export const UPLOAD_LINK_COPY: Record = { uploading: 'Envoi en cours…', attached: 'Terminé. Le fichier a été joint ; vous pouvez fermer cette page.', received: 'Terminé. Le fichier a été reçu ; revenez à l’assistant pour terminer.', + wantedSeveral: (max) => + `Des fichiers ont été demandés, pour être placés dans un champ fichier d’un enregistrement. Choisissez-en jusqu’à ${max} et envoyez-les ensemble.`, + wantedExactly: (n) => + `${n} fichiers ont été demandés, pour être placés dans un champ fichier d’un enregistrement. Choisissez les ${n} et envoyez-les ensemble.`, + filesLabel: 'Fichiers', + attachedSeveral: 'Terminé. Les fichiers ont été joints ; vous pouvez fermer cette page.', + receivedSeveral: 'Terminé. Les fichiers ont été reçus ; revenez à l’assistant pour terminer.', + pickCount: (min, max) => + min === max ? `Choisissez exactement ${min} fichiers.` : `Choisissez au plus ${max} fichiers.`, failed: 'L’envoi a échoué.', connectionLost: 'L’envoi a échoué : la connexion a été perdue. Demandez un nouveau lien si celui-ci ne fonctionne plus.', unusableTitle: 'Lien d’envoi', @@ -339,6 +413,14 @@ export const UPLOAD_LINK_COPY: Record = { uploading: 'Enviando…', attached: 'Pronto. O arquivo foi anexado; você pode fechar esta página.', received: 'Pronto. O arquivo foi recebido; volte ao assistente para concluir.', + wantedSeveral: (max) => + `Foram pedidos arquivos para serem colocados em um campo de arquivo de um registro. Escolha até ${max} e envie-os juntos.`, + wantedExactly: (n) => + `Foram pedidos ${n} arquivos para serem colocados em um campo de arquivo de um registro. Escolha os ${n} e envie-os juntos.`, + filesLabel: 'Arquivos', + attachedSeveral: 'Pronto. Os arquivos foram anexados; você pode fechar esta página.', + receivedSeveral: 'Pronto. Os arquivos foram recebidos; volte ao assistente para concluir.', + pickCount: (min, max) => (min === max ? `Escolha exatamente ${min} arquivos.` : `Escolha no máximo ${max} arquivos.`), failed: 'O envio falhou.', connectionLost: 'O envio falhou: a conexão foi perdida. Peça um novo link se este não funcionar mais.', unusableTitle: 'Link de envio', @@ -369,6 +451,15 @@ export const UPLOAD_LINK_COPY: Record = { uploading: 'Загрузка…', attached: 'Готово. Файл прикреплён; эту страницу можно закрыть.', received: 'Готово. Файл получен; вернитесь к ассистенту, чтобы завершить.', + wantedSeveral: (max) => + `Запрошены файлы для поля-файла записи. Выберите до ${max} файлов и отправьте их вместе.`, + wantedExactly: (n) => + `Запрошено файлов для поля-файла записи: ${n}. Выберите все ${n} и отправьте их вместе.`, + filesLabel: 'Файлы', + attachedSeveral: 'Готово. Файлы прикреплены; эту страницу можно закрыть.', + receivedSeveral: 'Готово. Файлы получены; вернитесь к ассистенту, чтобы завершить.', + pickCount: (min, max) => + min === max ? `Выберите ровно столько файлов: ${min}.` : `Выберите не больше файлов, чем ${max}.`, failed: 'Не удалось загрузить файл.', connectionLost: 'Не удалось загрузить файл: соединение прервалось. Если эта ссылка больше не работает, попросите новую.', unusableTitle: 'Ссылка для загрузки', @@ -399,6 +490,15 @@ export const UPLOAD_LINK_COPY: Record = { uploading: 'Wird hochgeladen…', attached: 'Fertig. Die Datei wurde angehängt; Sie können diese Seite schließen.', received: 'Fertig. Die Datei ist angekommen; kehren Sie zum Assistenten zurück, um abzuschließen.', + wantedSeveral: (max) => + `Es wurden Dateien angefordert, die in ein Dateifeld eines Datensatzes gelegt werden sollen. Wählen Sie bis zu ${max} aus und senden Sie sie zusammen.`, + wantedExactly: (n) => + `Es wurden ${n} Dateien angefordert, die in ein Dateifeld eines Datensatzes gelegt werden sollen. Wählen Sie alle ${n} aus und senden Sie sie zusammen.`, + filesLabel: 'Dateien', + attachedSeveral: 'Fertig. Die Dateien wurden angehängt; Sie können diese Seite schließen.', + receivedSeveral: 'Fertig. Die Dateien sind angekommen; kehren Sie zum Assistenten zurück, um abzuschließen.', + pickCount: (min, max) => + min === max ? `Wählen Sie genau ${min} Dateien aus.` : `Wählen Sie höchstens ${max} Dateien aus.`, failed: 'Das Hochladen ist fehlgeschlagen.', connectionLost: 'Das Hochladen ist fehlgeschlagen: Die Verbindung wurde unterbrochen. Fordern Sie einen neuen Link an, wenn dieser nicht mehr funktioniert.', unusableTitle: 'Upload-Link', diff --git a/packages/services/service-storage/src/upload-link-page.ts b/packages/services/service-storage/src/upload-link-page.ts index 0770d8f3f90..6c7c0f23191 100644 --- a/packages/services/service-storage/src/upload-link-page.ts +++ b/packages/services/service-storage/src/upload-link-page.ts @@ -33,6 +33,13 @@ import { formatUploadLinkExpiry, type UploadLinkCopy } from './upload-link-copy. * writes. An upload's refusal is shown as the answer's `userMessage`, which * the `PUT` door composes in the same language; an answer without one shows * the page's own "the upload failed". + * + * [#32747] A link to a multi-file field takes several files in its one + * submit: the picker takes `multiple`, the page says how many the link takes + * (up to the cap for a record, exactly the count asked for a record not yet + * created), and the files go in one `PUT` as a form (`file0` … `fileN-1` and + * `count`, `upload-link-wire.ts`). A single-file link sends the file as the + * request body, as before. */ /** The response headers every upload-link page carries. */ @@ -80,24 +87,33 @@ function shell(copy: UploadLinkCopy, title: string, body: string, nonce: string, /** * The script: send the picked file to this page's own address, once. `text` - * is the page's status lines in its language, as a JSON literal. + * is the page's status lines in its language, and the number of files the + * link takes (`min`, `max`), as a JSON literal. [#32747] More than one file + * goes as one form: `file0` … `fileN-1`, each named URI-encoded, and `count`. */ function uploadScript(text: string): string { return [ '(function(){', `var T=${text};`, 'var input=document.getElementById("file"),button=document.getElementById("send"),status=document.getElementById("status");', - 'input.addEventListener("change",function(){button.disabled=!input.files||!input.files.length;});', + 'function picked(){return input.files?input.files.length:0;}', + 'input.addEventListener("change",function(){var n=picked();var fits=n>=T.min&&n<=T.max;', + 'button.disabled=!n||!fits;status.textContent=n&&!fits?T.pickCount:"";});', 'button.addEventListener("click",function(){', - 'var file=input.files&&input.files[0];if(!file)return;', + 'var n=picked();if(!n||nT.max)return;var files=input.files;', 'button.disabled=true;input.disabled=true;status.textContent=T.uploading;', - 'fetch(location.pathname,{method:"PUT",credentials:"same-origin",cache:"no-store",', - 'headers:{"content-type":file.type||"application/octet-stream","x-file-name":encodeURIComponent(file.name)},body:file})', + 'var request;', + 'if(T.max>1){var form=new FormData();form.append("count",String(n));', + 'for(var i=0;i1?T.attachedSeveral:T.attached;return;}', // [#32712] The refusal as the door wrote it for a person, in this page's // language; an answer that carries none gets the page's own sentence. 'var u=r.body&&r.body.error&&r.body.error.userMessage;status.textContent=typeof u==="string"&&u?u:T.failed;})', @@ -128,11 +144,20 @@ function newNonce(): string { /** The picker page for a usable link, in `copy`'s language. */ export function sendUploadLinkPage(res: IHttpResponse, view: UploadLinkView, copy: UploadLinkCopy): void { const nonce = newNonce(); + // [#32747] How many files the link takes. + const files = view.files; + const several = files.max > 1; + const wanted = !several + ? copy.wanted(view.target === 'attachments' ? 'attachments' : 'field') + : files.min === files.max + ? copy.wantedExactly(files.min) + : copy.wantedSeveral(files.max); const body = `

${escapeHtml(copy.pageTitle)}

` + - `

${escapeHtml(copy.wanted(view.target === 'attachments' ? 'attachments' : 'field'))} ${escapeHtml(copy.once)}

` + + `

${escapeHtml(wanted)} ${escapeHtml(copy.once)}

` + `

${escapeHtml(copy.expires(formatUploadLinkExpiry(copy, view.expiresAt)))}

` + - `` + + `` + + `` + `` + '

'; const text = scriptLiteral({ @@ -140,6 +165,10 @@ export function sendUploadLinkPage(res: IHttpResponse, view: UploadLinkView, cop // [#32686] A link that names no record attaches nothing: the file waits // for the record the assistant creates. attached: view.newRecord === true ? copy.received : copy.attached, + attachedSeveral: view.newRecord === true ? copy.receivedSeveral : copy.attachedSeveral, + min: files.min, + max: files.max, + pickCount: copy.pickCount(files.min, files.max), failed: copy.failed, connectionLost: copy.connectionLost, }); From 9973604cdf0c8f2f0f15c9d5cc4b22e2db6424ff Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 20:10:16 +0000 Subject: [PATCH 03/10] feat(storage,mcp): one upload link takes several files on a multi-file field A link for a multiple: true file field takes up to ten files in one submit, judged before the link is spent and landed in one write or not at all. A link for a record not yet created takes count and answers every id at once. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibzVFJSNs6XZjC8jkNJ --- .../32747-upload-link-multiple-files.md | 18 ++++++ content/docs/ai/connect-mcp.mdx | 19 ++++-- content/docs/permissions/system-context.mdx | 2 +- packages/mcp/src/file-content.ts | 4 +- packages/mcp/src/mcp-file-tools.test.ts | 64 +++++++++++++++++++ packages/mcp/src/mcp-http-tools.ts | 60 +++++++++++++---- packages/mcp/src/skill-md.ts | 26 ++++---- packages/runtime/src/domains/mcp.ts | 5 +- 8 files changed, 166 insertions(+), 32 deletions(-) create mode 100644 .changeset/32747-upload-link-multiple-files.md diff --git a/.changeset/32747-upload-link-multiple-files.md b/.changeset/32747-upload-link-multiple-files.md new file mode 100644 index 00000000000..c36c7df156f --- /dev/null +++ b/.changeset/32747-upload-link-multiple-files.md @@ -0,0 +1,18 @@ +--- +'@objectstack/service-storage': patch +'@objectstack/mcp': patch +'@objectstack/runtime': patch +--- + +feat(storage,mcp): one upload link takes several files on a multi-file field + +Clause-②: yes (widening) +Metadata-protocol: none + +A link `create_upload_link` makes for a file field declared `multiple: true` now takes several files in its one use: the user picks up to 10 on the link's page and sends them together, and each file gets its own file id. "Here are my three invoices" is one link and one pick instead of three. A single-file field link and an attachments link take one file, as before. + +One send spends the link once. Every file in it is checked before that: the workspace's maximum upload size, and the field's own `accept` and `maxSize`. One file the field cannot take, or more than 10 files (`400` `VALIDATION_ERROR`), refuses the whole send, stores nothing and leaves the link usable. After that the field gains all the files in one write, or none: a failure storing any of them, or the record's write refusing (a pending approval's lock, say), discards every file of the send, so the record shows what it held before and no file of the send is left. + +For a record not yet created, `create_upload_link` takes `count` (how many files, up to 10) with a multi-file field, and answers that many `fileIds` at once; the user picks exactly that many, and the agent creates the record with the field set to `fileIds`. Each id keeps the rules a single upload's id has: only that user's own write, into that field of that object, in one record, within an hour of the upload. Before the upload, every write naming one of the ids is refused, the uploader's own included, and nothing serves it. + +The link's page takes several files where the link does, in every language it is served in. The send is one form (`multipart/form-data`) carrying `count` and `file0` … `fileN-1`; a single-file link still sends the file as the request body. Every successful answer now also carries `fileIds`. diff --git a/content/docs/ai/connect-mcp.mdx b/content/docs/ai/connect-mcp.mdx index 169f85a4c79..7ae0fa933a9 100644 --- a/content/docs/ai/connect-mcp.mdx +++ b/content/docs/ai/connect-mcp.mdx @@ -275,7 +275,7 @@ storage service is installed: | `list_actions` / `run_action` | Discover and invoke your business actions by name | | `resume_run` | Finish a flow action that paused on a screen, by submitting the screen's values | | `read_file` | Read a file a record carries: its text (text files, PDF, Word `.docx`) or the image itself, with its size, the byte cap and a short-lived download link | -| `create_upload_link` | Hand the user a single-use link that uploads one file onto a record's file field or its attachments | +| `create_upload_link` | Hand the user a single-use link that uploads a file onto a record's file field or its attachments (up to 10 files, sent together, for a multi-file field) | ### Files: `read_file` and `create_upload_link` @@ -301,7 +301,15 @@ record means no file**, refused with the same `RECORD_NOT_FOUND`. write). It answers a link and its expiry (ten minutes). The user opens the link in a browser where they are signed in to this deployment, picks one file, and it lands on exactly that record and field, or as an attachment of - that record. On a phone, they sign in there first. The link works only for + that record. On a phone, they sign in there first. A link for a + `multiple: true` file field takes several files in its one use: the user + picks up to 10 and sends them together, every file is checked (the maximum + upload size, and the field's own `accept` and `maxSize`) before the link is + spent, and the field gains all of them in one write, or none: one file the + field cannot take, or more than 10 (`400` `VALIDATION_ERROR`), refuses the + whole send with the link still usable, and a failure after that leaves the + record as it was. A single-file field link and an attachments link take one + file. The link works only for the user it was made for, and only once: without a session it answers `401`, and a second use, an expired link, an unknown link and another user's link all get the same `404`. The upload is stored as that user, with their @@ -326,10 +334,13 @@ record means no file**, refused with the same `RECORD_NOT_FOUND`. `recordId`. That needs a user who may create records of the object and write the field, and a field that is not `readonly`; an attachments link still needs its record. The answer carries `fileIds`, the id the upload is - stored under. Once the user has uploaded (the page says the file was + stored under. For several files into a multi-file field, the agent sends + `count` (up to 10): `fileIds` then holds that many ids, and the user must + pick exactly that many. Once the user has uploaded (the page says the file was received), the agent calls `create_record` with the field set to `fileIds[0]`, or the array for a multi-file field; before the upload that - create is refused as an upload that never completed. The field's own + create is refused as an upload that never completed, as is every other + write naming one of the ids. The field's own `accept` and `maxSize` are checked when the file arrives, before the link is spent. Until a record holds the file, the id works only for that user's own `create_record` or `update_record` into that field of that object, within diff --git a/content/docs/permissions/system-context.mdx b/content/docs/permissions/system-context.mdx index aba2ae61116..fc153cc6b07 100644 --- a/content/docs/permissions/system-context.mdx +++ b/content/docs/permissions/system-context.mdx @@ -193,7 +193,7 @@ One of the largest consumers of the flag; | 47c | The inbound-mail IMAP sync: `syncMailbox` and `syncAll` admit the system context ALONE | service-mailbox | Get: the sync job reads every mailbox row (its organization, address and IMAP cursor), writes the cursor back, and hands each fetched message to `ingest` under the system context. Lose: nothing a user held — every other caller is refused (`PERMISSION_DENIED`), because a sync stores a mailbox's mail and moves its cursor | `syncMailbox`, `syncAll` | | 47d | The print service REFUSES the system context: `printRecordToFile` admits a human user acting for themselves alone | service-print | Get: nothing — a system caller is refused (`PERMISSION_DENIED`) before any page is read, session minted or browser started. Lose: nothing a user held — the PDF is rendered as the requesting user and never as the system, so a record is archived only by someone who could read it | `refuseUnlessHumanCaller` | | 47e | The caller-scoped attach verbs REFUSE the system context: `attachFileAs` and `assertMayAttach` admit a signed-in user alone, and so do the caller-scoped record-file verbs the MCP `read_file` and `create_upload_link` tools call (`listRecordFilesAs`, `readRecordFileAs`, `createUploadLinkAs`, `createUploadLinkForNewRecordAs`) | service-storage | Get: nothing — a system caller is refused (`PERMISSION_DENIED`); the system attaches through `attachFile`, whose rows name no user. Lose: nothing a user held — the caller-scoped verbs insert the attachment under the caller's context so every insert gate judges that user and both rows name them, and the record-file verbs read the record and judge the file as that user, and bind an upload link to them; `createUploadLinkForNewRecordAs` names no record, so it asks the object's create verdict and the field's writability as that user instead | `packages/services/service-storage/src/file-attachment-service.ts#requireUserContext`, `packages/services/service-storage/src/record-file-access.ts#requireUserContext` | -| 47f | The file-reference claim path asks no read verdict of a system write: a record write claims or copies a referenced file only as its caller may read it (the download door's verdict), and a system write carries no caller to ask | service-storage | Get: a system write claims or copies any file the organization-scoped lookup reaches, as before #25692; a deliberate server-side copy between records runs this way. The exception is a file uploaded through an upload link that names no record (#32686), and the id such a link answers before its upload: until a record has held the file, only its uploader's own write takes it, so a system write naming it is refused at the field. Once a record holds it, a system write copies it as any; once a record lets it go, it is judged as any released file. Lose: nothing a user held — a user write is judged by the download door's verdict, and a context-less programmatic write is not asked either | `referencingCallerOf` | +| 47f | The file-reference claim path asks no read verdict of a system write: a record write claims or copies a referenced file only as its caller may read it (the download door's verdict), and a system write carries no caller to ask | service-storage | Get: a system write claims or copies any file the organization-scoped lookup reaches, as before #25692; a deliberate server-side copy between records runs this way. The exception is a file uploaded through an upload link that names no record (#32686), and the ids such a link answers before its upload (its own, and those it reserves for a several-file upload): until a record has held the file, only its uploader's own write takes it, so a system write naming it is refused at the field. Once a record holds it, a system write copies it as any; once a record lets it go, it is judged as any released file. Lose: nothing a user held — a user write is judged by the download door's verdict, and a context-less programmatic write is not asked either | `referencingCallerOf` | | 47g | The `sys_file` storage-owned columns guard returns early on create: a system insert keeps the `key`, `mime_type`, `size`, `status` and `etag` it writes | service-storage | Get: the storage service's own inserts (the upload doors, the field-file copy and backfill) write those five columns. Lose: nothing a user held — a non-system create has them dropped and starts `pending`, and on update the same columns are `readonly`, so the UPDATE `readonly` strip keeps them for every non-system caller | `installSysFileStorageOwnedColumnsGuard` | ### 5. Actions, metadata plane, provenance, the organization wall diff --git a/packages/mcp/src/file-content.ts b/packages/mcp/src/file-content.ts index d218bf45d1c..be4b40a6eb2 100644 --- a/packages/mcp/src/file-content.ts +++ b/packages/mcp/src/file-content.ts @@ -345,8 +345,10 @@ export interface McpFileBridge { * [#32686] A single-use upload link for a file field of a record the caller * is about to create. Optional on its own: a host without it serves links * for existing records only, and `create_upload_link` then needs `recordId`. + * [#32747] `count`: how many files the user will upload through it (a + * multi-file field), answered as that many `fileIds`. */ - createUploadLinkForNewRecord?(object: string, target: { field: string }): Promise; + createUploadLinkForNewRecord?(object: string, target: { field: string; count?: number }): Promise; } /** One MCP tool-result content block `read_file` answers with. */ diff --git a/packages/mcp/src/mcp-file-tools.test.ts b/packages/mcp/src/mcp-file-tools.test.ts index 9e31d51124c..51538306882 100644 --- a/packages/mcp/src/mcp-file-tools.test.ts +++ b/packages/mcp/src/mcp-file-tools.test.ts @@ -570,6 +570,70 @@ describe('[#32686] create_upload_link for a record not yet created', () => { }); }); +describe('[#32747] create_upload_link: one link, several files', () => { + let runtime: MCPServerRuntime; + beforeEach(() => { + runtime = new MCPServerRuntime({ name: 'file-tools', version: '0.0.0' }); + }); + + /** A new-record bridge answering as many ids as `count` asks for. */ + function countingBridge() { + const bridge = newRecordBridge(); + Object.assign(bridge, { + async createUploadLinkForNewRecord(object: string, target: { field: string; count?: number }) { + bridge.calls.push(['createUploadLinkForNewRecord', object, target]); + return { + url: 'https://acme.test/api/v1/storage/upload-links/f1.sec', + expiresAt: '2026-11-13T12:10:00.000Z', + fileIds: Array.from({ length: target.count ?? 1 }, (_, i) => `f${i + 1}`), + }; + }, + } satisfies McpFileBridge); + return bridge; + } + + it('count passes through to the bridge and the answer carries every id, with instructions to pick them all', async () => { + const bridge = countingBridge(); + const result = await callTool(runtime, bridge, 'create_upload_link', { objectName: 'claim', field: 'scans', count: 3 }); + expect(result.isError).toBeFalsy(); + expect(bridge.calls).toEqual([['createUploadLinkForNewRecord', 'claim', { field: 'scans', count: 3 }]]); + const facts = factsOf(result); + expect(facts.fileIds).toEqual(['f1', 'f2', 'f3']); + expect(facts.instructions).toContain('pick all 3 files'); + expect(facts.instructions).toContain('set to fileIds (all 3)'); + }); + + it('no count asks the bridge as before', async () => { + const bridge = countingBridge(); + await callTool(runtime, bridge, 'create_upload_link', { objectName: 'claim', field: 'scans' }); + expect(bridge.calls).toEqual([['createUploadLinkForNewRecord', 'claim', { field: 'scans' }]]); + }); + + it('count with a recordId is refused before the bridge is asked', async () => { + const bridge = countingBridge(); + const result = await callTool(runtime, bridge, 'create_upload_link', { objectName: 'claim', recordId: 'c1', field: 'scans', count: 2 }); + expect(result.isError).toBe(true); + expect(textOf(result.content[0])).toContain('count is for a record not yet created'); + expect(bridge.calls).toEqual([]); + }); + + it('count is listed only where a link can name no record, and the description says a multi-file link takes several', async () => { + const served = await uploadLinkSchema(runtime, countingBridge()); + expect(Object.keys(served.inputSchema.properties)).toContain('count'); + expect(served.description).toContain('takes several files, up to 10'); + const notServed = await uploadLinkSchema(runtime, fullBridge()); + expect(Object.keys(notServed.inputSchema.properties)).not.toContain('count'); + expect(notServed.description).not.toContain('uploads one file'); + }); + + it('the skill teaches several files and count', () => { + const skill = renderSkillMarkdown({ fileTools: true, newRecordUploadLinks: true }); + expect(skill).toContain('takes up to 10 files'); + expect(skill).toContain('send\n `count` (up to 10)'); + expect(renderSkillMarkdown({ fileTools: true })).not.toContain('`count`'); + }); +}); + describe('the skill teaches the file tools exactly where they register', () => { it('names both for a host that carries them, and each only for the scope that registers it', () => { const all = renderSkillMarkdown({ fileTools: true }); diff --git a/packages/mcp/src/mcp-http-tools.ts b/packages/mcp/src/mcp-http-tools.ts index c61ebef78f5..60013a74310 100644 --- a/packages/mcp/src/mcp-http-tools.ts +++ b/packages/mcp/src/mcp-http-tools.ts @@ -3380,10 +3380,13 @@ export function registerFileTools( note('create_upload_link'), { description: - 'Create a link through which the user uploads one file onto a record: into a file field (field) or ' + - 'as an attachment (attachments: true). Give the link to the user to open in a browser where they are ' + - 'signed in to this deployment as themselves; it works only for them, once, for this record and this ' + - 'field (or its attachments) only, and expires (see expiresAt). The upload is stored as the user, so they ' + + 'Create a link through which the user uploads a file onto a record: into a file field (field) or ' + + 'as an attachment (attachments: true). A link for a multi-file field takes several files, up to 10, ' + + 'picked and sent together; a single-file field or the attachments take one. Give the link to the user to ' + + 'open in a browser where they are signed in to this deployment as themselves; it works only for them, ' + + 'once (one send, however many files it carries), for this record and this field (or its attachments) ' + + 'only, and expires (see expiresAt). One file the field does not take refuses the whole send, and nothing ' + + 'is attached. The upload is stored as the user, so they ' + 'must be able to edit the record. A field link also needs a field they may write, and gets no link for ' + 'a field declared read-only (readonly), a field read-only on this record in its current state ' + '(readonlyWhen), or a record a pending approval locks. An attachments link asks only what attaching ' + @@ -3393,9 +3396,11 @@ export function registerFileTools( (newRecordLinkFn ? ' For a record you have not created yet (a required file field), omit recordId and name the field: ' + 'the user must be able to create such records, and the answer carries fileIds, the id(s) the upload ' + - 'is stored under. Once the user has uploaded, create the record with the field set to fileIds[0] ' + - '(the array, for a multi-file field). The id works only for this user\'s own write into that field ' + - 'of that object, in one record, within an hour of the upload.' + 'is stored under. For several files into a multi-file field, send count (how many, up to 10): ' + + 'fileIds then holds that many ids, and the user must pick exactly that many. Once the user has ' + + 'uploaded, create the record with the field set to fileIds[0] (the array fileIds, for a multi-file ' + + 'field). Each id works only for this user\'s own write into that field of that object, in one ' + + 'record, within an hour of the upload.' : ''), inputSchema: strictToolInput( { @@ -3416,16 +3421,38 @@ export function registerFileTools( .literal(true) .optional() .describe('true to attach the upload to the record instead of filling a field'), + ...(newRecordLinkFn + ? { + count: z + .number() + .int() + .min(1) + .optional() + .describe( + 'For a record not yet created (no recordId), with a multi-file field: how many files the user ' + + 'will upload, up to 10 (default 1). The answer carries that many fileIds.', + ), + } + : {}), }, ), annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false }, }, - async ({ objectName, recordId, field, attachments }) => { + async ({ objectName, recordId, field, attachments, ...rest }) => { + // [#32747] Listed only where a link can name no record; validated by the listed schema. + const count = (rest as { count?: number }).count; const bad = guard(objectName); if (bad) return errorResult(bad); if ((field === undefined) === (attachments === undefined)) { return errorResult('Say where the upload lands: either field (a file field of the record) or attachments: true.'); } + // [#32747] count names the ids a link for a record not yet created answers. + if (count !== undefined && recordId !== undefined) { + return errorResult( + 'count is for a record not yet created (no recordId), whose file ids are answered up front. A link for ' + + 'an existing record\'s multi-file field takes up to 10 files without it.', + ); + } if (recordId === undefined) { // [#32686] No record yet: a file field only, where the bridge serves it. if (field === undefined) { @@ -3436,7 +3463,8 @@ export function registerFileTools( } if (!newRecordLinkFn) return errorResult('recordId is required: name the record the upload lands on.'); try { - const link = await newRecordLinkFn(objectName, { field }); + const link = await newRecordLinkFn(objectName, { field, ...(count !== undefined ? { count } : {}) }); + const several = link.fileIds.length > 1; return textResult({ url: link.url, expiresAt: link.expiresAt, @@ -3446,9 +3474,14 @@ export function registerFileTools( fileIds: link.fileIds, instructions: 'Give this link to the user to open in a browser where they are signed in to this deployment, and ' + - 'pick the file. It works only for them, once, until expiresAt. Once they have uploaded, create the ' + - `record with ${field} set to fileIds[0] (the array, for a multi-file field). Before the upload, ` + - 'that create is refused as an upload that never completed.', + (several + ? `pick all ${link.fileIds.length} files and send them together. ` + : 'pick the file. ') + + 'It works only for them, once, until expiresAt. Once they have uploaded, create the ' + + (several + ? `record with ${field} set to fileIds (all ${link.fileIds.length}). ` + : `record with ${field} set to fileIds[0] (the array, for a multi-file field). `) + + 'Before the upload, that create is refused as an upload that never completed.', }); } catch (err) { return errorResultWithCode(err); @@ -3466,7 +3499,8 @@ export function registerFileTools( ...(field !== undefined ? { field } : { attachments: true }), instructions: 'Give this link to the user to open in a browser where they are signed in to this deployment, and ' + - 'pick the file. It works only for them, once, until expiresAt.', + 'pick the file (for a multi-file field, up to 10 files, sent together). It works only for them, ' + + 'once, until expiresAt.', }); } catch (err) { return errorResultWithCode(err); diff --git a/packages/mcp/src/skill-md.ts b/packages/mcp/src/skill-md.ts index 20f890459b2..35345ab9cdf 100644 --- a/packages/mcp/src/skill-md.ts +++ b/packages/mcp/src/skill-md.ts @@ -221,11 +221,13 @@ const READ_FILE_TOOL_LINES = `- **read_file({ objectName, recordId, field?, file /** [#30892] `create_upload_link`'s entry, rendered where `registerFileTools` registers it (`data:write`). */ const UPLOAD_LINK_TOOL_LINES = `- **create_upload_link({ objectName, recordId, field? | attachments: true })** — - a link through which the user uploads one file onto a record: into a file - field, or as an attachment. Give the link to the user to open where they - are signed in to this deployment; it works only for them, once, for that - record and field only, and expires at \`expiresAt\`. The upload is stored - as the user, so they must be able to edit the record. + a link through which the user uploads a file onto a record: into a file + field, or as an attachment. A multi-file field's link takes up to 10 files, + picked and sent together; one the field does not take refuses them all. + Give the link to the user to open where they are signed in to this + deployment; it works only for them, once, for that record and field only, + and expires at \`expiresAt\`. The upload is stored as the user, so they + must be able to edit the record. `; /** @@ -235,12 +237,14 @@ const UPLOAD_LINK_TOOL_LINES = `- **create_upload_link({ objectName, recordId, f */ const NEW_RECORD_UPLOAD_LINK_LINES = ` For a record you have not created yet (a required file field, such as an expense line's invoice), omit \`recordId\` and name \`field\`: the answer - carries \`fileIds\`. Once the user has uploaded, call \`create_record\` with - the field set to \`fileIds[0]\` (the array, for a multi-file field); before - the upload, that create is refused as an upload that never completed. The - id goes only into that field of that object, in one record, by this - user's own write, within an hour of the upload. The user must be able to - create such records. + carries \`fileIds\`. For several files into a multi-file field, send + \`count\` (up to 10): \`fileIds\` holds that many, and the user picks exactly + that many. Once the user has uploaded, call \`create_record\` with the field + set to \`fileIds[0]\` (the array, for a multi-file field); before the + upload, that create is refused as an upload that never completed. Each id + goes only into that field of that object, in one record, by this user's + own write, within an hour of the upload. The user must be able to create + such records. `; /** diff --git a/packages/runtime/src/domains/mcp.ts b/packages/runtime/src/domains/mcp.ts index 00b5770f74b..237ab94a807 100644 --- a/packages/runtime/src/domains/mcp.ts +++ b/packages/runtime/src/domains/mcp.ts @@ -1392,7 +1392,7 @@ export interface McpRecordFileService { */ createUploadLinkForNewRecordAs?( object: string, - target: { field: string }, + target: { field: string; count?: number }, context: unknown, ): Promise<{ path: string; expiresAt: string; fileIds: string[] }>; } @@ -1509,7 +1509,8 @@ function recordFileMembers( // object's create verdict and the field's writability for the caller. ...(newRecordLinkAs ? { - createUploadLinkForNewRecord: async (object: string, target: { field: string }) => { + // [#32747] `count`: how many files the user will upload, each id answered now. + createUploadLinkForNewRecord: async (object: string, target: { field: string; count?: number }) => { const grant = await newRecordLinkAs(object, target, ec); return { url: absoluteUrl(grant.path, await publicOrigin(deps, context)), From 1cf21827327f9f0f31e1aab637a4e3ad08aa111b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 20:11:33 +0000 Subject: [PATCH 04/10] test(dogfood): one upload link, three PDFs Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibzVFJSNs6XZjC8jkNJ --- .../showcase-mcp-record-files.dogfood.test.ts | 103 +++++++++++++++++- 1 file changed, 102 insertions(+), 1 deletion(-) diff --git a/packages/qa/dogfood/test/showcase-mcp-record-files.dogfood.test.ts b/packages/qa/dogfood/test/showcase-mcp-record-files.dogfood.test.ts index 4349e42c396..6ab4804f8b8 100644 --- a/packages/qa/dogfood/test/showcase-mcp-record-files.dogfood.test.ts +++ b/packages/qa/dogfood/test/showcase-mcp-record-files.dogfood.test.ts @@ -37,6 +37,12 @@ // the link answered: two agent calls and one upload, over the real // `/api/v1/mcp` and the real upload-link route. // +// [#32747] And one link, three PDFs: a link for the claim's multi-file +// `invoices` takes the three invoices in one send, as the page's form sends +// them through the real transport (`multipart/form-data`, `file0` … `file2` +// and `count`), and lands all three in one write; a link for a claim not yet +// created takes `count: 3` and answers the three ids `create_record` names. +// // Not eligible for the shared showcase project: it boots its own plugins. import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'; @@ -552,7 +558,7 @@ describe('[#30892] showcase: an agent reads and attaches a record\'s files over const res = await put(path, pdf, { 'x-file-name': 'fp-0001.pdf' }); const body: any = await res.json(); expect(res.status, JSON.stringify(body)).toBe(200); - expect(body.data).toEqual({ fileId, size: pdf.length, field: 'invoice' }); + expect(body.data).toEqual({ fileId, fileIds: [fileId], size: pdf.length, field: 'invoice' }); expect(await fileRow(fileId)).toMatchObject({ status: 'committed', size: pdf.length, ref_id: null, name: 'fp-0001.pdf' }); // Agent call 2: the create names the file id; the record holds the file. @@ -597,4 +603,99 @@ describe('[#30892] showcase: an agent reads and attaches a record\'s files over expect((await ql.find('sys_file', { where: { name: 'upload-link', status: 'pending' }, ...SYS })).length).toBe(linksBefore); }); }); + + // [#32747] Ruling A: one link, several files, on a multi-file field. + describe('[#32747] one link, three PDFs (`dogfood_upload_claim.invoices`)', () => { + const invoicesOf = async (id: string): Promise => { + const row = await ql.findOne(UPLOAD_CLAIM, { where: { id }, ...SYS }); + const value = row?.invoices; + const list = Array.isArray(value) ? value : value == null ? [] : [value]; + return list.map((v: any) => String(typeof v === 'object' ? v.id : v)); + }; + /** The page's several-file send: one form, `count` and `file0` … `fileN-1`, each name URI-encoded. */ + const putForm = (path: string, picks: Array<{ name: string; bytes: Buffer }>, token: string | null = memberToken) => { + const form = new FormData(); + form.append('count', String(picks.length)); + picks.forEach((pick, i) => { + form.append(`file${i}`, new Blob([new Uint8Array(pick.bytes)], { type: 'application/pdf' }), encodeURIComponent(pick.name)); + }); + return stack.raw(path, { method: 'PUT', headers: authOf(token), body: form }); + }; + const threeInvoices = () => [ + { name: 'hotel-invoice.pdf', bytes: minimalPdf('Hotel invoice 268.00') }, + { name: 'taxi-invoice.pdf', bytes: minimalPdf('Taxi invoice 42.50') }, + { name: 'meal-invoice.pdf', bytes: minimalPdf('Meal invoice 96.00') }, + ]; + + it('a claim\'s link takes the three invoices in one send: three ids, three files on the field, each read back', async () => { + const users = (await ql.find('sys_user', { where: { email: MEMBER_EMAIL }, ...SYS })) as Array<{ id: string }>; + const created = await ql.insert(UPLOAD_CLAIM, { name: 'Trip to Turin', status: 'draft', created_by: users[0]!.id, owner_id: users[0]!.id }, SYS); + const claimId = String(created?.id ?? created?.record?.id ?? created); + + const { path } = await mint({ objectName: UPLOAD_CLAIM, recordId: claimId, field: 'invoices' }); + const page = await open(path); + expect(page.status).toBe(200); + const html = await page.text(); + expect(html).toContain(''); + expect(html).toContain('Pick up to 10'); + + const picks = threeInvoices(); + const res = await putForm(path, picks); + const body: any = await res.json(); + expect(res.status, JSON.stringify(body)).toBe(200); + const fileIds = body.data.fileIds as string[]; + expect(fileIds).toHaveLength(3); + expect(body.data.files).toEqual(fileIds.map((fileId, i) => ({ fileId, size: picks[i]!.bytes.length }))); + expect(await invoicesOf(claimId)).toEqual(fileIds); + for (const [i, fileId] of fileIds.entries()) { + expect(await fileRow(fileId)).toMatchObject({ status: 'committed', name: picks[i]!.name, ref_object: UPLOAD_CLAIM, ref_id: claimId, ref_field: 'invoices' }); + const read = await ok(memberToken, 'read_file', { objectName: UPLOAD_CLAIM, recordId: claimId, field: 'invoices', fileId }); + expect(read.content.map((c: any) => c.text ?? '').join('\n')).toContain(['Hotel', 'Taxi', 'Meal'][i]); + } + // One send spent the link. + expect((await putForm(path, picks.slice(0, 1))).status).toBe(404); + }); + + it('a claim not yet created: count 3 answers three ids, one send fills them, create_record names all three', async () => { + const { path, answer } = await mint({ objectName: UPLOAD_CLAIM, field: 'invoices', count: 3 }); + expect(answer.fileIds).toHaveLength(3); + expect(answer.instructions).toContain('pick all 3 files'); + const page = await (await open(path)).text(); + expect(page).toContain('3 files were asked for'); + + const res = await putForm(path, threeInvoices()); + const body: any = await res.json(); + expect(res.status, JSON.stringify(body)).toBe(200); + expect(body.data.fileIds).toEqual(answer.fileIds); + + const { json } = await ok(memberToken, 'create_record', { + objectName: UPLOAD_CLAIM, + data: { name: 'Trip to Genoa', status: 'draft', invoices: answer.fileIds }, + }); + const claimId = String(json.id ?? json.record?.id); + expect(await invoicesOf(claimId)).toEqual(answer.fileIds); + }); + + it('one PDF of three the size limit refuses: nothing lands and the same link then takes the three', async () => { + const users = (await ql.find('sys_user', { where: { email: MEMBER_EMAIL }, ...SYS })) as Array<{ id: string }>; + const created = await ql.insert(UPLOAD_CLAIM, { name: 'Trip to Bari', status: 'draft', created_by: users[0]!.id, owner_id: users[0]!.id }, SYS); + const claimId = String(created?.id ?? created?.record?.id ?? created); + const { path } = await mint({ objectName: UPLOAD_CLAIM, recordId: claimId, field: 'invoices' }); + storage.setLimitsSnapshot({ maxUploadMb: { value: 0.002, authored: true } }); + try { + const picks = threeInvoices(); + picks[1] = { name: 'big-invoice.pdf', bytes: Buffer.concat([picks[1]!.bytes, Buffer.alloc(4096, 32)]) }; + const res = await putForm(path, picks); + const body: any = await res.json(); + expect(res.status, JSON.stringify(body)).toBe(413); + expect(await invoicesOf(claimId)).toEqual([]); + expect(await ql.find('sys_file', { where: { name: { $in: picks.map((p) => p.name) } }, ...SYS })).toEqual([]); + } finally { + storage.setLimitsSnapshot({}); + } + const res = await putForm(path, threeInvoices()); + expect(res.status, JSON.stringify(await res.clone().json())).toBe(200); + expect(await invoicesOf(claimId)).toHaveLength(3); + }); + }); }); From 8f7c187721dda72d91ff7527c74eb5784183e544 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 20:20:33 +0000 Subject: [PATCH 05/10] test(dogfood): judge the refused send by its own claim Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibzVFJSNs6XZjC8jkNJ --- .../dogfood/test/showcase-mcp-record-files.dogfood.test.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/packages/qa/dogfood/test/showcase-mcp-record-files.dogfood.test.ts b/packages/qa/dogfood/test/showcase-mcp-record-files.dogfood.test.ts index 6ab4804f8b8..185c01b0679 100644 --- a/packages/qa/dogfood/test/showcase-mcp-record-files.dogfood.test.ts +++ b/packages/qa/dogfood/test/showcase-mcp-record-files.dogfood.test.ts @@ -689,7 +689,11 @@ describe('[#30892] showcase: an agent reads and attaches a record\'s files over const body: any = await res.json(); expect(res.status, JSON.stringify(body)).toBe(413); expect(await invoicesOf(claimId)).toEqual([]); - expect(await ql.find('sys_file', { where: { name: { $in: picks.map((p) => p.name) } }, ...SYS })).toEqual([]); + // Nothing of the send is stored: no file names the claim, and the + // refused PDF's name is nowhere (the other two names recur in the + // earlier cases' claims, so they are judged by the claim instead). + expect(await ql.find('sys_file', { where: { ref_object: UPLOAD_CLAIM, ref_id: claimId }, ...SYS })).toEqual([]); + expect(await ql.find('sys_file', { where: { name: 'big-invoice.pdf' }, ...SYS })).toEqual([]); } finally { storage.setLimitsSnapshot({}); } From 6a6df23affbd19a8d4842f8746eed3e78e005ebd Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 20:25:10 +0000 Subject: [PATCH 06/10] test(storage): type the several-file pins against the storage seam Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibzVFJSNs6XZjC8jkNJ --- .../src/record-file-access.integration.test.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/services/service-storage/src/record-file-access.integration.test.ts b/packages/services/service-storage/src/record-file-access.integration.test.ts index 760f977e34d..57804417abe 100644 --- a/packages/services/service-storage/src/record-file-access.integration.test.ts +++ b/packages/services/service-storage/src/record-file-access.integration.test.ts @@ -1199,7 +1199,7 @@ describe('#30892 — a record\'s files for a resolved caller: read one, attach o const useLinkForm = (token: string, picks: Pick[], user: string | null = OWNER.userId, extra: Record = {}) => { const body: Record = { count: String(picks.length), ...extra }; picks.forEach((pick, i) => { - body[`file${i}`] = new File([pick.bytes], encodeURIComponent(pick.name), { type: pick.type ?? 'application/pdf' }); + body[`file${i}`] = new File([new Uint8Array(pick.bytes)], encodeURIComponent(pick.name), { type: pick.type ?? 'application/pdf' }); }); return call('PUT', `${BASE}/upload-links/:token`, { params: { token }, @@ -1374,7 +1374,7 @@ describe('#30892 — a record\'s files for a resolved caller: read one, attach o const upload = storage.upload.bind(storage); const keys: string[] = []; let calls = 0; - vi.spyOn(storage, 'upload').mockImplementation(async (key: string, data: Buffer, opts?: any) => { + vi.spyOn(storage, 'upload').mockImplementation(async (key, data, opts) => { calls += 1; if (calls === 2) throw new Error('disk full'); keys.push(key); @@ -1392,7 +1392,7 @@ describe('#30892 — a record\'s files for a resolved caller: read one, attach o const pre = await files.createUploadLinkForNewRecordAs('claim', { field: 'scans', count: 3 }, OWNER as never); calls = 0; keys.length = 0; - vi.spyOn(storage, 'upload').mockImplementation(async (key: string, data: Buffer, opts?: any) => { + vi.spyOn(storage, 'upload').mockImplementation(async (key, data, opts) => { calls += 1; if (calls === 2) throw new Error('disk full'); keys.push(key); From b97f7338e75b13b7b90558cf81b8049306435d01 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 21:14:26 +0000 Subject: [PATCH 07/10] fix(storage,mcp): several-file links judge every file before the spend, refuse a form to a one-file link, read no part before the form is judged Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibzVFJSNs6XZjC8jkNJ --- packages/mcp/src/mcp-file-tools.test.ts | 2 + packages/mcp/src/mcp-http-tools.ts | 2 + .../src/file-attachment-service.ts | 4 +- .../record-file-access.integration.test.ts | 108 +++++++++++++++++- .../service-storage/src/record-file-access.ts | 82 +++++++------ .../service-storage/src/storage-routes.ts | 88 +++++++++----- .../service-storage/src/upload-link-wire.ts | 23 ++++ 7 files changed, 248 insertions(+), 61 deletions(-) diff --git a/packages/mcp/src/mcp-file-tools.test.ts b/packages/mcp/src/mcp-file-tools.test.ts index 51538306882..71a6cfb7e10 100644 --- a/packages/mcp/src/mcp-file-tools.test.ts +++ b/packages/mcp/src/mcp-file-tools.test.ts @@ -620,6 +620,8 @@ describe('[#32747] create_upload_link: one link, several files', () => { it('count is listed only where a link can name no record, and the description says a multi-file link takes several', async () => { const served = await uploadLinkSchema(runtime, countingBridge()); expect(Object.keys(served.inputSchema.properties)).toContain('count'); + // The storage door's cap (UPLOAD_LINK_MAX_FILES), declared where the agent reads it. + expect(served.inputSchema.properties.count).toMatchObject({ type: 'integer', minimum: 1, maximum: 10 }); expect(served.description).toContain('takes several files, up to 10'); const notServed = await uploadLinkSchema(runtime, fullBridge()); expect(Object.keys(notServed.inputSchema.properties)).not.toContain('count'); diff --git a/packages/mcp/src/mcp-http-tools.ts b/packages/mcp/src/mcp-http-tools.ts index 60013a74310..b3782be9ad2 100644 --- a/packages/mcp/src/mcp-http-tools.ts +++ b/packages/mcp/src/mcp-http-tools.ts @@ -3423,10 +3423,12 @@ export function registerFileTools( .describe('true to attach the upload to the record instead of filling a field'), ...(newRecordLinkFn ? { + // 10 is the storage door's UPLOAD_LINK_MAX_FILES; the mint refuses more. count: z .number() .int() .min(1) + .max(10) .optional() .describe( 'For a record not yet created (no recordId), with a multi-file field: how many files the user ' + diff --git a/packages/services/service-storage/src/file-attachment-service.ts b/packages/services/service-storage/src/file-attachment-service.ts index c47c7b427e6..20c0773d81c 100644 --- a/packages/services/service-storage/src/file-attachment-service.ts +++ b/packages/services/service-storage/src/file-attachment-service.ts @@ -55,6 +55,7 @@ import { type RecordFileTarget, type UploadLinkDoor, type UploadLinkFilesOutcome, + type UploadLinkSubmitOptions, type UploadLinkGrant, type UploadLinkOutcome, type UploadLinkTarget, @@ -385,8 +386,9 @@ export class FileAttachmentService token: string, uploads: UploadLinkUpload[], callerUserId: string, + options?: UploadLinkSubmitOptions, ): Promise { - return this.recordFilesOrRefuse().consumeUploadLinkFiles(token, uploads, callerUserId); + return this.recordFilesOrRefuse().consumeUploadLinkFiles(token, uploads, callerUserId, options); } async attachFile(input: AttachFileInput): Promise { diff --git a/packages/services/service-storage/src/record-file-access.integration.test.ts b/packages/services/service-storage/src/record-file-access.integration.test.ts index 57804417abe..5d23c3d9f6a 100644 --- a/packages/services/service-storage/src/record-file-access.integration.test.ts +++ b/packages/services/service-storage/src/record-file-access.integration.test.ts @@ -72,7 +72,7 @@ import { installDefaultOrganization, DEFAULT_ORGANIZATION_ID } from './default-o import { UPLOAD_LINK_TTL_SECONDS } from './record-file-access.js'; import { PRE_RECORD_CLAIM_WINDOW_SECONDS } from './pre-record-upload.js'; import { resolveThrownHttpError } from '@objectstack/types'; -import { UPLOAD_LINK_MAX_FILES, UPLOAD_LINK_UNUSABLE_MESSAGE } from './upload-link-wire.js'; +import { UPLOAD_LINK_MAX_FILES, UPLOAD_LINK_ONE_FILE_FORM_MESSAGE, UPLOAD_LINK_UNUSABLE_MESSAGE } from './upload-link-wire.js'; import { UPLOAD_LINK_COPY } from './upload-link-copy.js'; const BASE = '/api/v1/storage'; @@ -1208,6 +1208,30 @@ describe('#30892 — a record\'s files for a resolved caller: read one, attach o }); }; const failureOf = (write: Promise) => write.then(() => null, (e: unknown) => resolveThrownHttpError(e)); + /** A form body sent exactly as given (parts, `count`), with extra headers. */ + const putForm = (token: string, body: Record, headers: Record = {}) => + call('PUT', `${BASE}/upload-links/:token`, { + params: { token }, + headers: { 'content-type': 'multipart/form-data; boundary=----os', ...headers, ...sessionOf(OWNER.userId) }, + body, + }); + /** File parts `file0` … that count how often their bytes are read. */ + const countedParts = (n: number) => { + const reads = { count: 0 }; + const parts: Record = {}; + for (let i = 0; i < n; i++) { + const file = new File([new Uint8Array(Buffer.from(`%PDF-1.4 cp-${i}`))], `cp-${i}.pdf`, { type: 'application/pdf' }); + parts[`file${i}`] = { + name: file.name, + type: file.type, + arrayBuffer: () => { + reads.count += 1; + return file.arrayBuffer(); + }, + }; + } + return { reads, parts }; + }; /** The `sys_file` rows named one of `names`: a submit's files, by the unique names a case picks. */ const rowsNamed = async (names: string[]) => ((await engine.find('sys_file', { where: { name: { $in: names } }, context: SYS } as never)) as Array>); @@ -1373,13 +1397,16 @@ describe('#30892 — a record\'s files for a resolved caller: read one, attach o const grant = await files.createUploadLinkAs('claim', id, { field: 'scans' }, OWNER as never); const upload = storage.upload.bind(storage); const keys: string[] = []; + const tried: string[] = []; let calls = 0; vi.spyOn(storage, 'upload').mockImplementation(async (key, data, opts) => { calls += 1; + tried.push(key); if (calls === 2) throw new Error('disk full'); keys.push(key); return upload(key, data, opts); }); + const deleted = vi.spyOn(storage, 'delete'); const picks = [pdf('sf-1.pdf'), pdf('sf-2.pdf'), pdf('sf-3.pdf')]; const res = await useLinkForm(tokenOf(grant.path), picks); expect(res._status).toBe(500); @@ -1387,21 +1414,29 @@ describe('#30892 — a record\'s files for a resolved caller: read one, attach o expect(await rowsNamed(picks.map((p) => p.name))).toEqual([]); expect(keys).toHaveLength(1); expect(await storage.exists(keys[0])).toBe(false); + // The upload that threw may have written part of its bytes: its key is deleted too. + expect(tried).toHaveLength(2); + expect(deleted.mock.calls.map(([key]) => key)).toEqual(tried); vi.restoreAllMocks(); // A link naming no record: every id of the submit is gone, the reserved ones not reached included. const pre = await files.createUploadLinkForNewRecordAs('claim', { field: 'scans', count: 3 }, OWNER as never); calls = 0; keys.length = 0; + tried.length = 0; vi.spyOn(storage, 'upload').mockImplementation(async (key, data, opts) => { calls += 1; + tried.push(key); if (calls === 2) throw new Error('disk full'); keys.push(key); return upload(key, data, opts); }); + const preDeleted = vi.spyOn(storage, 'delete'); const preRes = await useLinkForm(tokenOf(pre.path), [pdf('spf-1.pdf'), pdf('spf-2.pdf'), pdf('spf-3.pdf')]); expect(preRes._status).toBe(500); for (const fileId of pre.fileIds) expect(await fileRow(fileId)).toBeUndefined(); expect(await storage.exists(keys[0])).toBe(false); + expect(tried).toHaveLength(2); + expect(preDeleted.mock.calls.map(([key]) => key)).toEqual(tried); }); it('the record\'s write refusing after the spend (a lock): 409, the record unchanged, none of the files kept', async () => { @@ -1430,6 +1465,77 @@ describe('#30892 — a record\'s files for a resolved caller: read one, attach o expect(ok._status, JSON.stringify(ok._json)).toBe(200); }); + it('a multi-file field\'s record link judges the field\'s accept before the spend for one file too: refused, nothing stored, the link unspent', async () => { + const id = await newClaim('one-png'); + const grant = await files.createUploadLinkAs('claim', id, { field: 'scans' }, OWNER as never); + const png = { name: 'one.png', bytes: Buffer.from('png'), type: 'image/png' }; + for (const refused of [ + await useLinkForm(tokenOf(grant.path), [png]), + await useLink(tokenOf(grant.path), Buffer.from('png'), { 'content-type': 'image/png', 'x-file-name': 'one.png' }), + ]) { + expect(refused._status, JSON.stringify(refused._json)).toBe(400); + expect(refused._json.error.code).toBe('ERR_FILE_CONSTRAINT'); + } + expect((await claim(id)).scans ?? null).toBeNull(); + expect(await rowsNamed(['one.png'])).toEqual([]); + const ok = await useLinkForm(tokenOf(grant.path), [pdf('one-ok.pdf')]); + expect(ok._status, JSON.stringify(ok._json)).toBe(200); + }); + + it('a link that takes one file refuses a form even of one file, 400 VALIDATION_ERROR before the spend, and then takes the body', async () => { + for (const target of [{ field: 'policy' }, { attachments: true as const }]) { + const grant = await files.createUploadLinkAs('claim', ids.claimB, target, OWNER as never); + const form = await useLinkForm(tokenOf(grant.path), [pdf('form-one.pdf')]); + expect(form._status, JSON.stringify(form._json)).toBe(400); + expect(form._json.error.code).toBe('VALIDATION_ERROR'); + expect(form._json.error.message).toBe(UPLOAD_LINK_ONE_FILE_FORM_MESSAGE); + expect(await rowsNamed(['form-one.pdf'])).toEqual([]); + const body = await useLink(tokenOf(grant.path), Buffer.from('%PDF-1.4 body')); + expect(body._status, JSON.stringify(body._json)).toBe(200); + } + }); + + it('a form declares at most this link\'s files: one file\'s allowance on a one-file link, the cap\'s on a multi-file link', async () => { + storage.setLimitsSnapshot({ maxUploadMb: { value: 1, authored: true } } as never); + try { + const declared = { 'content-length': String(2 * MIB) }; + const single = await files.createUploadLinkAs('claim', ids.claimB, { field: 'policy' }, OWNER as never); + const one = await putForm(tokenOf(single.path), { count: '1', ...countedParts(1).parts }, declared); + expect(one._status, JSON.stringify(one._json)).toBe(413); + const several = await files.createUploadLinkAs('claim', await newClaim('declared'), { field: 'scans' }, OWNER as never); + const two = await putForm(tokenOf(several.path), { count: '2', ...countedParts(2).parts }, declared); + expect(two._status, JSON.stringify(two._json)).toBe(200); + } finally { + storage.setLimitsSnapshot({} as never); + } + }); + + it('a form is refused before any part is read: a count over the link\'s cap, parts that disagree with count, a part missing', async () => { + const grant = await files.createUploadLinkAs('claim', await newClaim('unread'), { field: 'scans' }, OWNER as never); + const token = tokenOf(grant.path); + const over = countedParts(UPLOAD_LINK_MAX_FILES + 1); + const tooMany = await putForm(token, { count: String(UPLOAD_LINK_MAX_FILES + 1), ...over.parts }); + expect(tooMany._status, JSON.stringify(tooMany._json)).toBe(400); + expect(tooMany._json.error.code).toBe('VALIDATION_ERROR'); + expect(tooMany._json.error.message).toContain(`takes up to ${UPLOAD_LINK_MAX_FILES} files`); + expect(over.reads.count).toBe(0); + const huge = countedParts(2); + const hugeCount = await putForm(token, { count: '999', ...huge.parts }); + expect(hugeCount._json.error.code).toBe('VALIDATION_ERROR'); + expect(huge.reads.count).toBe(0); + const lost = countedParts(2); + const lostRes = await putForm(token, { count: '3', ...lost.parts }); + expect(lostRes._json.error.code).toBe('INVALID_REQUEST'); + expect(lost.reads.count).toBe(0); + const gap = countedParts(3); + const gapRes = await putForm(token, { count: '2', file0: gap.parts.file0, file2: gap.parts.file2 }); + expect(gapRes._json.error.code).toBe('INVALID_REQUEST'); + expect(gap.reads.count).toBe(0); + const ok = countedParts(2); + expect((await putForm(token, { count: '2', ...ok.parts }))._status).toBe(200); + expect(ok.reads.count).toBe(2); + }); + it('the page: a multi-file field link picks several, a link naming no record asks for its count, a single-file link picks one', async () => { const id = await newClaim('page'); const several = await openLink(tokenOf((await files.createUploadLinkAs('claim', id, { field: 'scans' }, OWNER as never)).path)); diff --git a/packages/services/service-storage/src/record-file-access.ts b/packages/services/service-storage/src/record-file-access.ts index 7113e0ba263..becb3cc35b7 100644 --- a/packages/services/service-storage/src/record-file-access.ts +++ b/packages/services/service-storage/src/record-file-access.ts @@ -43,6 +43,8 @@ import { buildKey, mintDownloadUrl } from './storage-routes.js'; import { UPLOAD_LINK_FILE_COUNT_CODE, UPLOAD_LINK_FILE_COUNT_STATUS, + UPLOAD_LINK_ONE_FILE_FORM_MESSAGE, + uploadLinkFileCountMessage, UPLOAD_LINK_KIND, UPLOAD_LINK_MAX_FILES, UPLOAD_LINK_SEGMENT, @@ -158,15 +160,20 @@ import { assertFileConstraints } from './file-reference-lifecycle.js'; * A single-file field link and an attachments link take one, as before. * * - **One submit spends the link once.** Every file in it is judged before - * the spend: the doors' size verdict for each, and, for a submit carrying - * more than one file, the field's own `accept` / `maxSize` for each. One - * refusal refuses the whole submit, nothing is stored, and the link stays - * usable. A submit carrying one file is judged exactly as it was before - * this rule (the record's write judges the field's constraints). + * the spend: the doors' size verdict for each, and, on a link that takes + * several, the field's own `accept` / `maxSize` for each, however many the + * submit carries. One refusal refuses the whole submit, nothing is stored, + * and the link stays usable. A link that takes one file is judged exactly + * as it was before this rule (to a record, the record's write judges the + * field's constraints), and takes its file as the request body: a form is + * refused before the spend. + * - **The several-file form** names `count`, at most the link's cap, and the + * door refuses a form whose `count` is over the link's cap or whose parts + * disagree with it before it reads any part's bytes. * - **All or nothing after the spend.** A link naming a record stores every * file, then writes the field once, appending all of them. When any store - * or the write fails, every file the submit stored is discarded, bytes and - * row, so the record holds what it held before and no row of the submit is + * or the write fails, every file of the submit is discarded, bytes and + * row (a key whose upload was tried is deleted even when the upload threw), so the record holds what it held before and no row of the submit is * left. * - **A link naming no record answers every id when it is minted**: the * agent asks for `count` files, the link row is the first id and `count - 1` @@ -372,6 +379,11 @@ export interface ICallerRecordFileService { * minted for, signed in, so the token alone opens nothing. Another user gets * the one unusable-link refusal, and the link is not spent. */ +/** [#32747] How a submit was sent: as the request body (one file) or as a several-file form. */ +export interface UploadLinkSubmitOptions { + sentAs?: 'body' | 'form'; +} + export interface UploadLinkDoor { /** The link's view, or the one unusable-link refusal. Writes nothing. */ inspectUploadLink(token: string, callerUserId: string): Promise; @@ -380,8 +392,14 @@ export interface UploadLinkDoor { /** * [#32747] Spend the link on one submit carrying `uploads` (in the order * picked), landing all of them where the link is bound, or none. + * `sentAs: 'form'` is a several-file form, which a one-file link refuses. */ - consumeUploadLinkFiles(token: string, uploads: UploadLinkUpload[], callerUserId: string): Promise; + consumeUploadLinkFiles( + token: string, + uploads: UploadLinkUpload[], + callerUserId: string, + options?: UploadLinkSubmitOptions, + ): Promise; } /** The data-engine surface these verbs use: the reads and writes every engine has, plus its schema read. */ @@ -598,17 +616,7 @@ function isOpenReservation(row: FileRecord | null, linkId: string, userId: strin * not take, before the link is spent. */ function refuseFileCount(range: { min: number; max: number }, sent: number): never { - const taken = - range.max === 1 - ? 'takes one file' - : range.min === range.max - ? `takes exactly ${range.min} files, sent together` - : `takes up to ${range.max} files, sent together`; - refuse( - UPLOAD_LINK_FILE_COUNT_CODE, - UPLOAD_LINK_FILE_COUNT_STATUS, - `Nothing was stored: this upload link ${taken}, and ${sent} ${sent === 1 ? 'was' : 'were'} sent.`, - ); + refuse(UPLOAD_LINK_FILE_COUNT_CODE, UPLOAD_LINK_FILE_COUNT_STATUS, uploadLinkFileCountMessage(range, sent)); } /** `sys_file.metadata` for a link's binding. */ @@ -1144,6 +1152,7 @@ export class RecordFileAccess implements ICallerRecordFileService, UploadLinkDoo token: string, uploads: UploadLinkUpload[], callerUserId: string, + options: UploadLinkSubmitOptions = {}, ): Promise { const engine = this.engineOrRefuse(); const storage = this.storageOrRefuse(); @@ -1154,6 +1163,11 @@ export class RecordFileAccess implements ICallerRecordFileService, UploadLinkDoo // [#32747] As many files as the link takes, before anything else is judged. const range = this.fileRangeOf(engine, state); if (uploads.length < range.min || uploads.length > range.max) refuseFileCount(range, uploads.length); + // A link that takes one file takes it as the request body, as it did + // before links took several: a form, even of one file, is refused. + if (options.sentAs === 'form' && range.max === 1) { + refuse(UPLOAD_LINK_FILE_COUNT_CODE, UPLOAD_LINK_FILE_COUNT_STATUS, UPLOAD_LINK_ONE_FILE_FORM_MESSAGE); + } const maxUploadBytes = resolveStorageLimits(this.deps.getLimitsSnapshot()).maxUploadBytes; for (const upload of uploads) { if (!nonEmptyString(upload?.filename)) refuse('VALIDATION_ERROR', 400, 'The upload names no file.'); @@ -1183,11 +1197,13 @@ export class RecordFileAccess implements ICallerRecordFileService, UploadLinkDoo // judges the field's own `accept` / `maxSize` until the create does: they // are judged here, before the link is spent, as the record's write would // judge them, and a file the field cannot take is refused with nothing - // stored. [#32747] So are they for each file of a submit carrying several: + // stored. [#32747] So are they for each file sent through a link that + // takes several (a multi-file field's), however many the submit carries: // one file the field cannot take refuses them all with the link unspent. - // A one-file submit to a record is judged by the record's write, as before. + // A link that takes one file to a record is judged by the record's write, + // as before. const newRecord = state.record_id === undefined; - if (newRecord || typed.length > 1) { + if (newRecord || range.max > 1) { const def = requireFileField(engine, state.object, state.field as string); for (const upload of typed) { assertFileConstraints(def, state.field as string, { @@ -1266,12 +1282,12 @@ export class RecordFileAccess implements ICallerRecordFileService, UploadLinkDoo const field = state.field as string; const claimUntil = new Date(this.now() + PRE_RECORD_CLAIM_WINDOW_SECONDS * 1000).toISOString(); const keys = fileIds.map((fileId, i) => buildKey(FIELD_UPLOAD_SCOPE, fileId, uploads[i].filename)); - let stored = 0; + let attempted = 0; try { for (let i = 0; i < fileIds.length; i++) { const upload = uploads[i]; + attempted = i + 1; await storage.upload(keys[i], upload.data, { contentType: upload.mimeType }); - stored = i + 1; await store.updateFile( fileIds[i], { @@ -1294,7 +1310,7 @@ export class RecordFileAccess implements ICallerRecordFileService, UploadLinkDoo } } catch (err) { for (let i = 0; i < fileIds.length; i++) { - await this.discard(storage, store, fileIds[i], keys[i], writeContext, i < stored); + await this.discard(storage, store, fileIds[i], keys[i], writeContext, i < attempted); } throw err; } @@ -1358,7 +1374,7 @@ export class RecordFileAccess implements ICallerRecordFileService, UploadLinkDoo const def = requireFileField(engine, state.object, field); const files = uploads.map((upload) => { const fileId = randomUUID(); - return { fileId, key: buildKey(FIELD_UPLOAD_SCOPE, fileId, upload.filename), upload, created: false, stored: false }; + return { fileId, key: buildKey(FIELD_UPLOAD_SCOPE, fileId, upload.filename), upload, created: false, attempted: false }; }); try { for (const file of files) { @@ -1378,8 +1394,8 @@ export class RecordFileAccess implements ICallerRecordFileService, UploadLinkDoo writeContext, ); file.created = true; + file.attempted = true; await storage.upload(file.key, upload.data, { contentType: upload.mimeType }); - file.stored = true; // A record write takes only a completed upload. await store.updateFile(file.fileId, { status: 'committed' }, writeContext); } @@ -1405,7 +1421,7 @@ export class RecordFileAccess implements ICallerRecordFileService, UploadLinkDoo } } catch (err) { for (const file of files) { - if (file.created) await this.discard(storage, store, file.fileId, file.key, writeContext, file.stored); + if (file.created) await this.discard(storage, store, file.fileId, file.key, writeContext, file.attempted); } readonlyRefusalOf(err, state.object, field); throw err; @@ -1420,8 +1436,10 @@ export class RecordFileAccess implements ICallerRecordFileService, UploadLinkDoo /** * Undo a refused field upload: the bytes, then the row. Best-effort; the - * refusal is what is thrown. [#32747] `bytesStored` false: the row is all - * there is to take back (its bytes never landed). + * refusal is what is thrown. [#32747] `uploadAttempted` false: the row is + * all there is to take back (no upload of its bytes was tried). A tried + * upload's key is deleted even when the upload threw, as it may have + * written part of the bytes. */ private async discard( storage: IStorageService, @@ -1429,10 +1447,10 @@ export class RecordFileAccess implements ICallerRecordFileService, UploadLinkDoo fileId: string, key: string, writeContext: StorageWriteContext, - bytesStored = true, + uploadAttempted = true, ): Promise { try { - if (bytesStored) await storage.delete(key); + if (uploadAttempted) await storage.delete(key); } catch (err) { this.deps.logger.warn( `[storage] upload link: a refused upload could not delete its stored bytes (${(err as Error)?.message ?? err}). ` + diff --git a/packages/services/service-storage/src/storage-routes.ts b/packages/services/service-storage/src/storage-routes.ts index 7928751cb88..bf83d710902 100644 --- a/packages/services/service-storage/src/storage-routes.ts +++ b/packages/services/service-storage/src/storage-routes.ts @@ -68,12 +68,14 @@ export { buildKey }; import type { UploadLinkDoor, UploadLinkUpload, UploadLinkView } from './record-file-access.js'; import { UPLOAD_LINK_FORM_COUNT_FIELD, + UPLOAD_LINK_FILE_COUNT_CODE, + UPLOAD_LINK_FILE_COUNT_STATUS, UPLOAD_LINK_FORM_FILE_PREFIX, - UPLOAD_LINK_MAX_FILES, UPLOAD_LINK_SEGMENT, UPLOAD_LINK_UNUSABLE_CODE, UPLOAD_LINK_UNUSABLE_MESSAGE, UPLOAD_LINK_UNUSABLE_STATUS, + uploadLinkFileCountMessage, } from './upload-link-wire.js'; import { sendUnusableUploadLinkPage, sendUploadLinkPage } from './upload-link-page.js'; import { uploadLinkCopy, uploadLinkRefusalText, type UploadLinkCopy } from './upload-link-copy.js'; @@ -1882,38 +1884,43 @@ export function registerStorageFamily( }); return; } - // The declared length first, so an oversized body is refused before it - // is read; the service judges the bytes read again, before the link is - // spent, so an oversized upload never uses it up. [#32747] A - // several-file submit (a form) may carry up to the link's cap of files, - // each within the limit; the service judges each file. + // The declared length first: this door refuses a body that declares more + // than it takes before this door reads it. The service judges the bytes + // read again, before the link is spent, so an oversized upload never uses + // it up. [#32747] A several-file submit (a form) declares up to as many + // files as THIS link takes, each within the limit, plus the form's + // framing: the link is read first (a read that writes nothing), so a + // link that takes one file gets a one-file allowance here, and the + // service refuses it the form. + const token = String(req.params.token ?? ''); const { maxUploadBytes } = currentLimits(); const declaredBody = declaredContentLength(req); const several = isUploadLinkForm(req.headers?.['content-type']); + const linkFiles = several ? (await door.inspectUploadLink(token, caller.userId as string)).files : undefined; const formLimit = - several && maxUploadBytes !== undefined - ? maxUploadBytes * UPLOAD_LINK_MAX_FILES + UPLOAD_LINK_FORM_OVERHEAD_BYTES + linkFiles !== undefined && maxUploadBytes !== undefined + ? maxUploadBytes * linkFiles.max + UPLOAD_LINK_FORM_OVERHEAD_BYTES : undefined; const tooLarge = declaredBody === undefined ? null : formLimit !== undefined ? declaredBody > formLimit - ? `The upload body is ${declaredBody} bytes, over the ${formLimit} bytes a several-file upload can carry ` + - `(${UPLOAD_LINK_MAX_FILES} files, each within the "Max upload size (MB)" storage setting).` + ? `The upload body is ${declaredBody} bytes, over the ${formLimit} bytes this link's upload can carry ` + + `(${linkFiles!.max} ${linkFiles!.max === 1 ? 'file' : 'files'}, each within the "Max upload size (MB)" storage setting).` : null : uploadSizeRefusal(declaredBody, maxUploadBytes, (n) => `The upload body is ${n} bytes`); if (tooLarge !== null) { sendError(res, UPLOAD_TOO_LARGE_STATUS, UPLOAD_TOO_LARGE_CODE, tooLarge, { userMessage: copy.tooLarge }); return; } - if (several) { - const uploads = await uploadLinkFormFiles(req.body); - if (typeof uploads === 'string') { - sendError(res, 400, 'INVALID_REQUEST', uploads, { userMessage: copy.refused(uploads) }); + if (linkFiles !== undefined) { + const uploads = await uploadLinkFormFiles(req.body, linkFiles); + if (!Array.isArray(uploads)) { + sendError(res, uploads.status, uploads.code, uploads.message, { userMessage: copy.refused(uploads.message) }); return; } - const outcome = await door.consumeUploadLinkFiles(String(req.params.token ?? ''), uploads, caller.userId as string); + const outcome = await door.consumeUploadLinkFiles(token, uploads, caller.userId as string, { sentAs: 'form' }); const fileIds = outcome.files.map((file) => file.fileId); sendOk(res, { fileId: fileIds[0], @@ -1935,7 +1942,7 @@ export function registerStorageFamily( return; } const outcome = await door.consumeUploadLink( - String(req.params.token ?? ''), + token, { filename: uploadLinkFilename(req.headers?.['x-file-name']), mimeType: uploadLinkMimeType(req.headers?.['content-type']), @@ -2470,37 +2477,64 @@ function isFormFilePart(value: unknown): value is FormFilePart { return !!value && typeof value === 'object' && typeof (value as FormFilePart).arrayBuffer === 'function'; } +/** [#32747] Why a several-file form is refused before any of its parts is read. */ +interface UploadLinkFormRefusal { + status: number; + code: StandardErrorCode | RegisteredErrorCode; + message: string; +} + /** * [#32747] The files of a several-file submit, in the order sent, or the * reason the form is not one: `count` must name how many files it carries - * (a whole number), and parts `file0` … `fileN-1` must each be a file, with - * no other file part beside them, so a part a parser dropped (or one sent - * twice under one name, of which a parser keeps only the last) is refused - * rather than stored as fewer files than were picked. How many files the - * link takes is the service's to judge. + * (a whole number, at most what the link takes), and parts `file0` … + * `fileN-1` must each be a file, with no other file part beside them, so a + * part a parser dropped (or one sent twice under one name, of which a parser + * keeps only the last) is refused rather than stored as fewer files than were + * picked. Every one of those refusals comes before any part's bytes are read + * here. A `count` over what the link takes gets the link's file-count + * refusal; the service judges the exact count again before the spend. */ -async function uploadLinkFormFiles(body: unknown): Promise { +async function uploadLinkFormFiles( + body: unknown, + linkFiles: { min: number; max: number }, +): Promise { + const malformed = (message: string): UploadLinkFormRefusal => ({ status: 400, code: 'INVALID_REQUEST', message }); const form = body && typeof body === 'object' ? (body as Record) : {}; const rawCount = form[UPLOAD_LINK_FORM_COUNT_FIELD]; const countText = Array.isArray(rawCount) ? undefined : typeof rawCount === 'string' ? rawCount.trim() : undefined; const count = countText !== undefined && /^[0-9]{1,3}$/.test(countText) ? Number(countText) : NaN; if (!Number.isInteger(count) || count < 1) { - return ( + return malformed( `A several-file upload is a form naming how many files it carries (${UPLOAD_LINK_FORM_COUNT_FIELD}) ` + - `and each file as ${UPLOAD_LINK_FORM_FILE_PREFIX}0, ${UPLOAD_LINK_FORM_FILE_PREFIX}1, …` + `and each file as ${UPLOAD_LINK_FORM_FILE_PREFIX}0, ${UPLOAD_LINK_FORM_FILE_PREFIX}1, …`, ); } + if (count > linkFiles.max) { + return { + status: UPLOAD_LINK_FILE_COUNT_STATUS, + code: UPLOAD_LINK_FILE_COUNT_CODE, + message: uploadLinkFileCountMessage(linkFiles, count), + }; + } const partName = new RegExp(`^${UPLOAD_LINK_FORM_FILE_PREFIX}(0|[1-9][0-9]*)$`); const fileParts = Object.entries(form).filter(([key, value]) => isFormFilePart(value) || partName.test(key)); if (fileParts.length !== count) { - return `The form names ${count} file(s) in ${UPLOAD_LINK_FORM_COUNT_FIELD} but carries ${fileParts.length}.`; + return malformed(`The form names ${count} file(s) in ${UPLOAD_LINK_FORM_COUNT_FIELD} but carries ${fileParts.length}.`); } - const uploads: UploadLinkUpload[] = []; + const parts: FormFilePart[] = []; for (let i = 0; i < count; i++) { const part = form[`${UPLOAD_LINK_FORM_FILE_PREFIX}${i}`]; if (!isFormFilePart(part)) { - return `The form carries no file ${UPLOAD_LINK_FORM_FILE_PREFIX}${i}: the files are ${UPLOAD_LINK_FORM_FILE_PREFIX}0 … ${UPLOAD_LINK_FORM_FILE_PREFIX}${count - 1}.`; + return malformed( + `The form carries no file ${UPLOAD_LINK_FORM_FILE_PREFIX}${i}: the files are ` + + `${UPLOAD_LINK_FORM_FILE_PREFIX}0 … ${UPLOAD_LINK_FORM_FILE_PREFIX}${count - 1}.`, + ); } + parts.push(part); + } + const uploads: UploadLinkUpload[] = []; + for (const part of parts) { uploads.push({ filename: uploadLinkFilename(typeof part.name === 'string' ? part.name : undefined), mimeType: uploadLinkMimeType(typeof part.type === 'string' ? part.type : undefined), diff --git a/packages/services/service-storage/src/upload-link-wire.ts b/packages/services/service-storage/src/upload-link-wire.ts index b4fa158166b..e8fafe61087 100644 --- a/packages/services/service-storage/src/upload-link-wire.ts +++ b/packages/services/service-storage/src/upload-link-wire.ts @@ -39,6 +39,29 @@ export const UPLOAD_LINK_MAX_FILES = 10; export const UPLOAD_LINK_FILE_COUNT_STATUS = 400; export const UPLOAD_LINK_FILE_COUNT_CODE: StandardErrorCode = 'VALIDATION_ERROR'; +/** + * [#32747] That refusal's words, for a link that takes from `range.min` to + * `range.max` files and a submit carrying `sent`. One spelling for the door + * that reads the form and the service that spends the link. + */ +export function uploadLinkFileCountMessage(range: { min: number; max: number }, sent: number): string { + const taken = + range.max === 1 + ? 'takes one file' + : range.min === range.max + ? `takes exactly ${range.min} files, sent together` + : `takes up to ${range.max} files, sent together`; + return `Nothing was stored: this upload link ${taken}, and ${sent} ${sent === 1 ? 'was' : 'were'} sent.`; +} + +/** + * [#32747] The refusal of a several-file form sent to a link that takes one + * file (a single-file field's, or an attachments link): that link takes its + * file as the request body. Same code and status as a wrong count. + */ +export const UPLOAD_LINK_ONE_FILE_FORM_MESSAGE = + 'Nothing was stored: this upload link takes one file, sent as the request body, not as a several-file form.'; + /** * [#32747] The multipart form a several-file submit is sent as: one part per * file named `file0` … `fileN-1`, in the order picked, and a `count` field From 501eafef1730a2a6b19d663b0a52612c08d8750b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 21:16:34 +0000 Subject: [PATCH 08/10] docs(storage): say exactly which links judge every file before the spend Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibzVFJSNs6XZjC8jkNJ --- .changeset/32747-upload-link-multiple-files.md | 4 ++-- content/docs/ai/connect-mcp.mdx | 6 +++--- .../dogfood/test/showcase-mcp-record-files.dogfood.test.ts | 2 +- packages/services/service-storage/src/upload-link-wire.ts | 3 +-- 4 files changed, 7 insertions(+), 8 deletions(-) diff --git a/.changeset/32747-upload-link-multiple-files.md b/.changeset/32747-upload-link-multiple-files.md index c36c7df156f..e8962441bc0 100644 --- a/.changeset/32747-upload-link-multiple-files.md +++ b/.changeset/32747-upload-link-multiple-files.md @@ -11,8 +11,8 @@ Metadata-protocol: none A link `create_upload_link` makes for a file field declared `multiple: true` now takes several files in its one use: the user picks up to 10 on the link's page and sends them together, and each file gets its own file id. "Here are my three invoices" is one link and one pick instead of three. A single-file field link and an attachments link take one file, as before. -One send spends the link once. Every file in it is checked before that: the workspace's maximum upload size, and the field's own `accept` and `maxSize`. One file the field cannot take, or more than 10 files (`400` `VALIDATION_ERROR`), refuses the whole send, stores nothing and leaves the link usable. After that the field gains all the files in one write, or none: a failure storing any of them, or the record's write refusing (a pending approval's lock, say), discards every file of the send, so the record shows what it held before and no file of the send is left. +On a multi-file field's link, one send spends the link once, and every file in it, however many the send carries, is checked before that: the workspace's maximum upload size, and the field's own `accept` and `maxSize`. One file the field cannot take, or more than 10 files (`400` `VALIDATION_ERROR`), refuses the whole send, stores nothing and leaves the link usable. After that the field gains all the files in one write, or none: a failure storing any of them, or the record's write refusing (a pending approval's lock, say), discards every file of the send, so the record shows what it held before and no file of the send is left. For a record not yet created, `create_upload_link` takes `count` (how many files, up to 10) with a multi-file field, and answers that many `fileIds` at once; the user picks exactly that many, and the agent creates the record with the field set to `fileIds`. Each id keeps the rules a single upload's id has: only that user's own write, into that field of that object, in one record, within an hour of the upload. Before the upload, every write naming one of the ids is refused, the uploader's own included, and nothing serves it. -The link's page takes several files where the link does, in every language it is served in. The send is one form (`multipart/form-data`) carrying `count` and `file0` … `fileN-1`; a single-file link still sends the file as the request body. Every successful answer now also carries `fileIds`. +The link's page takes several files where the link does, in every language it is served in. The send is one form (`multipart/form-data`) carrying `count` and `file0` … `fileN-1`; a single-file field link and an attachments link take their file as the request body, as before (a form sent to one is refused `400` `VALIDATION_ERROR` before the link is spent), and are checked as before. Every successful answer now also carries `fileIds`. diff --git a/content/docs/ai/connect-mcp.mdx b/content/docs/ai/connect-mcp.mdx index 7ae0fa933a9..f644eb05dd5 100644 --- a/content/docs/ai/connect-mcp.mdx +++ b/content/docs/ai/connect-mcp.mdx @@ -303,9 +303,9 @@ record means no file**, refused with the same `RECORD_NOT_FOUND`. file, and it lands on exactly that record and field, or as an attachment of that record. On a phone, they sign in there first. A link for a `multiple: true` file field takes several files in its one use: the user - picks up to 10 and sends them together, every file is checked (the maximum - upload size, and the field's own `accept` and `maxSize`) before the link is - spent, and the field gains all of them in one write, or none: one file the + picks up to 10 and sends them together, every file of the send, however + many, is checked (the maximum upload size, and the field's own `accept` and + `maxSize`) before the link is spent, and the field gains all of them in one write, or none: one file the field cannot take, or more than 10 (`400` `VALIDATION_ERROR`), refuses the whole send with the link still usable, and a failure after that leaves the record as it was. A single-file field link and an attachments link take one diff --git a/packages/qa/dogfood/test/showcase-mcp-record-files.dogfood.test.ts b/packages/qa/dogfood/test/showcase-mcp-record-files.dogfood.test.ts index 185c01b0679..951554ffa3e 100644 --- a/packages/qa/dogfood/test/showcase-mcp-record-files.dogfood.test.ts +++ b/packages/qa/dogfood/test/showcase-mcp-record-files.dogfood.test.ts @@ -39,7 +39,7 @@ // // [#32747] And one link, three PDFs: a link for the claim's multi-file // `invoices` takes the three invoices in one send, as the page's form sends -// them through the real transport (`multipart/form-data`, `file0` … `file2` +// them through the served stack (`multipart/form-data`, `file0` … `file2` // and `count`), and lands all three in one write; a link for a claim not yet // created takes `count: 3` and answers the three ids `create_record` names. // diff --git a/packages/services/service-storage/src/upload-link-wire.ts b/packages/services/service-storage/src/upload-link-wire.ts index e8fafe61087..03263118fbb 100644 --- a/packages/services/service-storage/src/upload-link-wire.ts +++ b/packages/services/service-storage/src/upload-link-wire.ts @@ -66,8 +66,7 @@ export const UPLOAD_LINK_ONE_FILE_FORM_MESSAGE = * [#32747] The multipart form a several-file submit is sent as: one part per * file named `file0` … `fileN-1`, in the order picked, and a `count` field * naming N. Indexed names, because a form parser that keeps one value per - * name (Hono's `parseBody`, both transports) keeps only the last of a - * repeated one; `count` lets the door refuse a body that lost a part rather + * name keeps only the last of a repeated one; `count` lets the door refuse a body that lost a part rather * than store fewer files than were sent. Each part's file name is * URI-encoded, as the single-file submit's `x-file-name` header is. */ From 5cc654121039c794c8998b72f823f8397334752a Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 21:54:23 +0000 Subject: [PATCH 09/10] fix(storage): only a link that takes several files reads a form; a one-file link takes any body as the file, as before Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibzVFJSNs6XZjC8jkNJ --- .../32747-upload-link-multiple-files.md | 2 +- .../src/file-attachment-service.ts | 4 +- .../record-file-access.integration.test.ts | 56 +++++++++++-------- .../service-storage/src/record-file-access.ts | 18 +----- .../service-storage/src/storage-routes.ts | 41 +++++++++++--- .../service-storage/src/upload-link-wire.ts | 14 ++--- 6 files changed, 74 insertions(+), 61 deletions(-) diff --git a/.changeset/32747-upload-link-multiple-files.md b/.changeset/32747-upload-link-multiple-files.md index e8962441bc0..729f6aad92c 100644 --- a/.changeset/32747-upload-link-multiple-files.md +++ b/.changeset/32747-upload-link-multiple-files.md @@ -15,4 +15,4 @@ On a multi-file field's link, one send spends the link once, and every file in i For a record not yet created, `create_upload_link` takes `count` (how many files, up to 10) with a multi-file field, and answers that many `fileIds` at once; the user picks exactly that many, and the agent creates the record with the field set to `fileIds`. Each id keeps the rules a single upload's id has: only that user's own write, into that field of that object, in one record, within an hour of the upload. Before the upload, every write naming one of the ids is refused, the uploader's own included, and nothing serves it. -The link's page takes several files where the link does, in every language it is served in. The send is one form (`multipart/form-data`) carrying `count` and `file0` … `fileN-1`; a single-file field link and an attachments link take their file as the request body, as before (a form sent to one is refused `400` `VALIDATION_ERROR` before the link is spent), and are checked as before. Every successful answer now also carries `fileIds`. +The link's page takes several files where the link does, in every language it is served in. The send is one form (`multipart/form-data`) carrying `count` and `file0` … `fileN-1`; a single-file field link and an attachments link take the request body as the file, whatever its content type, under the same limit and with the same checks as before. Every successful answer now also carries `fileIds`. diff --git a/packages/services/service-storage/src/file-attachment-service.ts b/packages/services/service-storage/src/file-attachment-service.ts index 20c0773d81c..c47c7b427e6 100644 --- a/packages/services/service-storage/src/file-attachment-service.ts +++ b/packages/services/service-storage/src/file-attachment-service.ts @@ -55,7 +55,6 @@ import { type RecordFileTarget, type UploadLinkDoor, type UploadLinkFilesOutcome, - type UploadLinkSubmitOptions, type UploadLinkGrant, type UploadLinkOutcome, type UploadLinkTarget, @@ -386,9 +385,8 @@ export class FileAttachmentService token: string, uploads: UploadLinkUpload[], callerUserId: string, - options?: UploadLinkSubmitOptions, ): Promise { - return this.recordFilesOrRefuse().consumeUploadLinkFiles(token, uploads, callerUserId, options); + return this.recordFilesOrRefuse().consumeUploadLinkFiles(token, uploads, callerUserId); } async attachFile(input: AttachFileInput): Promise { diff --git a/packages/services/service-storage/src/record-file-access.integration.test.ts b/packages/services/service-storage/src/record-file-access.integration.test.ts index 5d23c3d9f6a..fa46f5aa0db 100644 --- a/packages/services/service-storage/src/record-file-access.integration.test.ts +++ b/packages/services/service-storage/src/record-file-access.integration.test.ts @@ -72,7 +72,8 @@ import { installDefaultOrganization, DEFAULT_ORGANIZATION_ID } from './default-o import { UPLOAD_LINK_TTL_SECONDS } from './record-file-access.js'; import { PRE_RECORD_CLAIM_WINDOW_SECONDS } from './pre-record-upload.js'; import { resolveThrownHttpError } from '@objectstack/types'; -import { UPLOAD_LINK_MAX_FILES, UPLOAD_LINK_ONE_FILE_FORM_MESSAGE, UPLOAD_LINK_UNUSABLE_MESSAGE } from './upload-link-wire.js'; +import { UPLOAD_LINK_MAX_FILES, UPLOAD_LINK_UNUSABLE_MESSAGE } from './upload-link-wire.js'; +import { uploadSizeRefusal } from './storage-limits.js'; import { UPLOAD_LINK_COPY } from './upload-link-copy.js'; const BASE = '/api/v1/storage'; @@ -1205,6 +1206,8 @@ describe('#30892 — a record\'s files for a resolved caller: read one, attach o params: { token }, headers: { 'content-type': 'multipart/form-data; boundary=----os', ...sessionOf(user) }, body, + // A transport hands the body's bytes too; a link that reads no form takes them. + rawBody: async () => Buffer.from('------os--\r\n'), }); }; const failureOf = (write: Promise) => write.then(() => null, (e: unknown) => resolveThrownHttpError(e)); @@ -1214,6 +1217,7 @@ describe('#30892 — a record\'s files for a resolved caller: read one, attach o params: { token }, headers: { 'content-type': 'multipart/form-data; boundary=----os', ...headers, ...sessionOf(OWNER.userId) }, body, + rawBody: async () => Buffer.from('------os--\r\n'), }); /** File parts `file0` … that count how often their bytes are read. */ const countedParts = (n: number) => { @@ -1346,10 +1350,11 @@ describe('#30892 — a record\'s files for a resolved caller: read one, attach o it('control: a single-file field link and an attachments link still take one file; a second is refused, and the one lands', async () => { for (const target of [{ field: 'policy' }, { attachments: true as const }]) { const grant = await files.createUploadLinkAs('claim', ids.claimB, target, OWNER as never); - const two = await useLinkForm(tokenOf(grant.path), [pdf('one-a.pdf'), pdf('one-b.pdf')]); - expect(two._status, JSON.stringify(two._json)).toBe(400); - expect(two._json.error.code).toBe('VALIDATION_ERROR'); - expect(two._json.error.message).toContain('takes one file'); + // The door never reads a form for such a link (below); the service it + // spends through refuses two files before the spend all the same. + const two = [pdf('one-a.pdf'), pdf('one-b.pdf')].map((p) => ({ filename: p.name, mimeType: 'application/pdf', data: p.bytes })); + expect(await refusalOf(files.consumeUploadLinkFiles(tokenOf(grant.path), two, OWNER.userId))) + .toMatchObject({ code: 'VALIDATION_ERROR', status: 400, message: expect.stringContaining('takes one file') }); expect(await rowsNamed(['one-a.pdf', 'one-b.pdf'])).toEqual([]); const one = await useLink(tokenOf(grant.path), Buffer.from('%PDF-1.4 one')); expect(one._status, JSON.stringify(one._json)).toBe(200); @@ -1482,34 +1487,41 @@ describe('#30892 — a record\'s files for a resolved caller: read one, attach o expect(ok._status, JSON.stringify(ok._json)).toBe(200); }); - it('a link that takes one file refuses a form even of one file, 400 VALIDATION_ERROR before the spend, and then takes the body', async () => { - for (const target of [{ field: 'policy' }, { attachments: true as const }]) { - const grant = await files.createUploadLinkAs('claim', ids.claimB, target, OWNER as never); - const form = await useLinkForm(tokenOf(grant.path), [pdf('form-one.pdf')]); - expect(form._status, JSON.stringify(form._json)).toBe(400); - expect(form._json.error.code).toBe('VALIDATION_ERROR'); - expect(form._json.error.message).toBe(UPLOAD_LINK_ONE_FILE_FORM_MESSAGE); - expect(await rowsNamed(['form-one.pdf'])).toEqual([]); - const body = await useLink(tokenOf(grant.path), Buffer.from('%PDF-1.4 body')); - expect(body._status, JSON.stringify(body._json)).toBe(200); + it('a link that takes one file takes its body as the file whatever its content type, a multipart body included, under the one-file limit, as before', async () => { + const multipart = 'multipart/form-data; boundary=----os'; + const raw = Buffer.from('------os\r\nContent-Disposition: form-data; name="count"\r\n\r\n1\r\n------os--\r\n'); + storage.setLimitsSnapshot({ maxUploadMb: { value: 1, authored: true } } as never); + try { + for (const target of [{ field: 'policy' }, { attachments: true as const }]) { + const grant = await files.createUploadLinkAs('claim', ids.claimB, target, OWNER as never); + const token = tokenOf(grant.path); + // Declared over the one-file limit but within a form's allowance for + // one file: refused, with the one-file words, before anything is read. + const over = await useLink(token, raw, { 'content-type': multipart, 'content-length': String(MIB + 1) }); + expect(over._status, JSON.stringify(over._json)).toBe(413); + expect(over._json.error.message).toBe(uploadSizeRefusal(MIB + 1, MIB, (n) => `The upload body is ${n} bytes`)); + // The body is the file: stored as sent, its size the body's length. + const res = await useLink(token, raw, { 'content-type': multipart }); + expect(res._status, JSON.stringify(res._json)).toBe(200); + expect(res._json.data.size).toBe(raw.length); + expect(res._json.data.fileIds).toEqual([res._json.data.fileId]); + expect((await useLink(token, raw, { 'content-type': multipart }))._status).toBe(404); + } + } finally { + storage.setLimitsSnapshot({} as never); } }); - it('a form declares at most this link\'s files: one file\'s allowance on a one-file link, the cap\'s on a multi-file link', async () => { + it('a form on a multi-file field\'s link declares up to that link\'s files, each within the limit', async () => { storage.setLimitsSnapshot({ maxUploadMb: { value: 1, authored: true } } as never); try { - const declared = { 'content-length': String(2 * MIB) }; - const single = await files.createUploadLinkAs('claim', ids.claimB, { field: 'policy' }, OWNER as never); - const one = await putForm(tokenOf(single.path), { count: '1', ...countedParts(1).parts }, declared); - expect(one._status, JSON.stringify(one._json)).toBe(413); const several = await files.createUploadLinkAs('claim', await newClaim('declared'), { field: 'scans' }, OWNER as never); - const two = await putForm(tokenOf(several.path), { count: '2', ...countedParts(2).parts }, declared); + const two = await putForm(tokenOf(several.path), { count: '2', ...countedParts(2).parts }, { 'content-length': String(2 * MIB) }); expect(two._status, JSON.stringify(two._json)).toBe(200); } finally { storage.setLimitsSnapshot({} as never); } }); - it('a form is refused before any part is read: a count over the link\'s cap, parts that disagree with count, a part missing', async () => { const grant = await files.createUploadLinkAs('claim', await newClaim('unread'), { field: 'scans' }, OWNER as never); const token = tokenOf(grant.path); diff --git a/packages/services/service-storage/src/record-file-access.ts b/packages/services/service-storage/src/record-file-access.ts index becb3cc35b7..f207940711f 100644 --- a/packages/services/service-storage/src/record-file-access.ts +++ b/packages/services/service-storage/src/record-file-access.ts @@ -43,7 +43,6 @@ import { buildKey, mintDownloadUrl } from './storage-routes.js'; import { UPLOAD_LINK_FILE_COUNT_CODE, UPLOAD_LINK_FILE_COUNT_STATUS, - UPLOAD_LINK_ONE_FILE_FORM_MESSAGE, uploadLinkFileCountMessage, UPLOAD_LINK_KIND, UPLOAD_LINK_MAX_FILES, @@ -165,8 +164,8 @@ import { assertFileConstraints } from './file-reference-lifecycle.js'; * submit carries. One refusal refuses the whole submit, nothing is stored, * and the link stays usable. A link that takes one file is judged exactly * as it was before this rule (to a record, the record's write judges the - * field's constraints), and takes its file as the request body: a form is - * refused before the spend. + * field's constraints), and takes its body as the file, whatever its + * content type, as it did before links took several. * - **The several-file form** names `count`, at most the link's cap, and the * door refuses a form whose `count` is over the link's cap or whose parts * disagree with it before it reads any part's bytes. @@ -379,11 +378,6 @@ export interface ICallerRecordFileService { * minted for, signed in, so the token alone opens nothing. Another user gets * the one unusable-link refusal, and the link is not spent. */ -/** [#32747] How a submit was sent: as the request body (one file) or as a several-file form. */ -export interface UploadLinkSubmitOptions { - sentAs?: 'body' | 'form'; -} - export interface UploadLinkDoor { /** The link's view, or the one unusable-link refusal. Writes nothing. */ inspectUploadLink(token: string, callerUserId: string): Promise; @@ -392,13 +386,11 @@ export interface UploadLinkDoor { /** * [#32747] Spend the link on one submit carrying `uploads` (in the order * picked), landing all of them where the link is bound, or none. - * `sentAs: 'form'` is a several-file form, which a one-file link refuses. */ consumeUploadLinkFiles( token: string, uploads: UploadLinkUpload[], callerUserId: string, - options?: UploadLinkSubmitOptions, ): Promise; } @@ -1152,7 +1144,6 @@ export class RecordFileAccess implements ICallerRecordFileService, UploadLinkDoo token: string, uploads: UploadLinkUpload[], callerUserId: string, - options: UploadLinkSubmitOptions = {}, ): Promise { const engine = this.engineOrRefuse(); const storage = this.storageOrRefuse(); @@ -1163,11 +1154,6 @@ export class RecordFileAccess implements ICallerRecordFileService, UploadLinkDoo // [#32747] As many files as the link takes, before anything else is judged. const range = this.fileRangeOf(engine, state); if (uploads.length < range.min || uploads.length > range.max) refuseFileCount(range, uploads.length); - // A link that takes one file takes it as the request body, as it did - // before links took several: a form, even of one file, is refused. - if (options.sentAs === 'form' && range.max === 1) { - refuse(UPLOAD_LINK_FILE_COUNT_CODE, UPLOAD_LINK_FILE_COUNT_STATUS, UPLOAD_LINK_ONE_FILE_FORM_MESSAGE); - } const maxUploadBytes = resolveStorageLimits(this.deps.getLimitsSnapshot()).maxUploadBytes; for (const upload of uploads) { if (!nonEmptyString(upload?.filename)) refuse('VALIDATION_ERROR', 400, 'The upload names no file.'); diff --git a/packages/services/service-storage/src/storage-routes.ts b/packages/services/service-storage/src/storage-routes.ts index bf83d710902..03f839826ad 100644 --- a/packages/services/service-storage/src/storage-routes.ts +++ b/packages/services/service-storage/src/storage-routes.ts @@ -1887,16 +1887,18 @@ export function registerStorageFamily( // The declared length first: this door refuses a body that declares more // than it takes before this door reads it. The service judges the bytes // read again, before the link is spent, so an oversized upload never uses - // it up. [#32747] A several-file submit (a form) declares up to as many - // files as THIS link takes, each within the limit, plus the form's - // framing: the link is read first (a read that writes nothing), so a - // link that takes one file gets a one-file allowance here, and the - // service refuses it the form. + // it up. [#32747] Which submit a link takes is the link's: only a link + // that takes several files reads a form (`multipart/form-data`), which + // may declare up to as many files as that link takes, each within the + // limit, plus the form's framing. A link that takes one file takes its + // body as the file, whatever its content type, under the one-file limit, + // exactly as before links took several. const token = String(req.params.token ?? ''); const { maxUploadBytes } = currentLimits(); const declaredBody = declaredContentLength(req); - const several = isUploadLinkForm(req.headers?.['content-type']); - const linkFiles = several ? (await door.inspectUploadLink(token, caller.userId as string)).files : undefined; + const linkFiles = isUploadLinkForm(req.headers?.['content-type']) + ? await severalFilesOf(door, token, caller.userId as string) + : undefined; const formLimit = linkFiles !== undefined && maxUploadBytes !== undefined ? maxUploadBytes * linkFiles.max + UPLOAD_LINK_FORM_OVERHEAD_BYTES @@ -1907,7 +1909,7 @@ export function registerStorageFamily( : formLimit !== undefined ? declaredBody > formLimit ? `The upload body is ${declaredBody} bytes, over the ${formLimit} bytes this link's upload can carry ` + - `(${linkFiles!.max} ${linkFiles!.max === 1 ? 'file' : 'files'}, each within the "Max upload size (MB)" storage setting).` + `(${linkFiles!.max} files, each within the "Max upload size (MB)" storage setting).` : null : uploadSizeRefusal(declaredBody, maxUploadBytes, (n) => `The upload body is ${n} bytes`); if (tooLarge !== null) { @@ -1920,7 +1922,7 @@ export function registerStorageFamily( sendError(res, uploads.status, uploads.code, uploads.message, { userMessage: copy.refused(uploads.message) }); return; } - const outcome = await door.consumeUploadLinkFiles(token, uploads, caller.userId as string, { sentAs: 'form' }); + const outcome = await door.consumeUploadLinkFiles(token, uploads, caller.userId as string); const fileIds = outcome.files.map((file) => file.fileId); sendOk(res, { fileId: fileIds[0], @@ -2460,6 +2462,27 @@ function relayUploadLinkRefusal(res: IHttpResponse, err: unknown, copy: UploadLi */ const UPLOAD_LINK_FORM_OVERHEAD_BYTES = 64 * 1024; +/** + * [#32747] How many files a link that takes several takes, read before a + * multipart body is judged (a read that writes nothing), or `undefined` for a + * link that takes one file. A link that cannot be read is `undefined` too: it + * takes the one-file path, whose spend answers the refusal it answered before + * links took several, in the order it did. + */ +async function severalFilesOf( + door: UploadLinkDoor, + token: string, + callerUserId: string, +): Promise<{ min: number; max: number } | undefined> { + let files: { min: number; max: number }; + try { + files = (await door.inspectUploadLink(token, callerUserId)).files; + } catch { + return undefined; + } + return files.max > 1 ? files : undefined; +} + /** [#32747] Is the submit a several-file form (`multipart/form-data`)? */ function isUploadLinkForm(raw: string | string[] | undefined): boolean { const first = Array.isArray(raw) ? raw[0] : raw; diff --git a/packages/services/service-storage/src/upload-link-wire.ts b/packages/services/service-storage/src/upload-link-wire.ts index 03263118fbb..d671cc057cc 100644 --- a/packages/services/service-storage/src/upload-link-wire.ts +++ b/packages/services/service-storage/src/upload-link-wire.ts @@ -54,20 +54,14 @@ export function uploadLinkFileCountMessage(range: { min: number; max: number }, return `Nothing was stored: this upload link ${taken}, and ${sent} ${sent === 1 ? 'was' : 'were'} sent.`; } -/** - * [#32747] The refusal of a several-file form sent to a link that takes one - * file (a single-file field's, or an attachments link): that link takes its - * file as the request body. Same code and status as a wrong count. - */ -export const UPLOAD_LINK_ONE_FILE_FORM_MESSAGE = - 'Nothing was stored: this upload link takes one file, sent as the request body, not as a several-file form.'; - /** * [#32747] The multipart form a several-file submit is sent as: one part per * file named `file0` … `fileN-1`, in the order picked, and a `count` field * naming N. Indexed names, because a form parser that keeps one value per - * name keeps only the last of a repeated one; `count` lets the door refuse a body that lost a part rather - * than store fewer files than were sent. Each part's file name is + * name keeps only the last of a repeated one; `count` lets the door refuse a + * body that lost a part rather than store fewer files than were sent. Only a + * link that takes several files reads the form; a link that takes one takes + * its body as the file, whatever its content type. Each part's file name is * URI-encoded, as the single-file submit's `x-file-name` header is. */ export const UPLOAD_LINK_FORM_COUNT_FIELD = 'count'; From 03dcadc63561eba754b2d93991e4877e1473a475 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 22:37:45 +0000 Subject: [PATCH 10/10] fix(storage): read the several-file form only when the page marks it; any other body is the file on every link Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibzVFJSNs6XZjC8jkNJ --- .../32747-upload-link-multiple-files.md | 2 +- .../showcase-mcp-record-files.dogfood.test.ts | 3 +- .../record-file-access.integration.test.ts | 67 ++++++++++++++++++- .../service-storage/src/record-file-access.ts | 10 ++- .../service-storage/src/storage-routes.ts | 35 +++++++--- .../service-storage/src/upload-link-page.ts | 6 +- .../service-storage/src/upload-link-wire.ts | 15 ++++- 7 files changed, 116 insertions(+), 22 deletions(-) diff --git a/.changeset/32747-upload-link-multiple-files.md b/.changeset/32747-upload-link-multiple-files.md index 729f6aad92c..906f4ba87b4 100644 --- a/.changeset/32747-upload-link-multiple-files.md +++ b/.changeset/32747-upload-link-multiple-files.md @@ -15,4 +15,4 @@ On a multi-file field's link, one send spends the link once, and every file in i For a record not yet created, `create_upload_link` takes `count` (how many files, up to 10) with a multi-file field, and answers that many `fileIds` at once; the user picks exactly that many, and the agent creates the record with the field set to `fileIds`. Each id keeps the rules a single upload's id has: only that user's own write, into that field of that object, in one record, within an hour of the upload. Before the upload, every write naming one of the ids is refused, the uploader's own included, and nothing serves it. -The link's page takes several files where the link does, in every language it is served in. The send is one form (`multipart/form-data`) carrying `count` and `file0` … `fileN-1`; a single-file field link and an attachments link take the request body as the file, whatever its content type, under the same limit and with the same checks as before. Every successful answer now also carries `fileIds`. +The link's page takes several files where the link does, in every language it is served in. The send is one form (`multipart/form-data`, marked by the header `x-upload-link-form: several`) carrying `count` and `file0` … `fileN-1`, and only a link that takes several files reads it. Any other body, on any link (a multipart one without that header included), is the file itself, whatever its content type, under the same limit and with the same checks as before. Every successful answer now also carries `fileIds`. diff --git a/packages/qa/dogfood/test/showcase-mcp-record-files.dogfood.test.ts b/packages/qa/dogfood/test/showcase-mcp-record-files.dogfood.test.ts index 951554ffa3e..05fc2d5d626 100644 --- a/packages/qa/dogfood/test/showcase-mcp-record-files.dogfood.test.ts +++ b/packages/qa/dogfood/test/showcase-mcp-record-files.dogfood.test.ts @@ -619,7 +619,8 @@ describe('[#30892] showcase: an agent reads and attaches a record\'s files over picks.forEach((pick, i) => { form.append(`file${i}`, new Blob([new Uint8Array(pick.bytes)], { type: 'application/pdf' }), encodeURIComponent(pick.name)); }); - return stack.raw(path, { method: 'PUT', headers: authOf(token), body: form }); + // The page's form says it is the form (`x-upload-link-form: several`); any other body is the file. + return stack.raw(path, { method: 'PUT', headers: { ...authOf(token), 'x-upload-link-form': 'several' }, body: form }); }; const threeInvoices = () => [ { name: 'hotel-invoice.pdf', bytes: minimalPdf('Hotel invoice 268.00') }, diff --git a/packages/services/service-storage/src/record-file-access.integration.test.ts b/packages/services/service-storage/src/record-file-access.integration.test.ts index fa46f5aa0db..a5dfffc7807 100644 --- a/packages/services/service-storage/src/record-file-access.integration.test.ts +++ b/packages/services/service-storage/src/record-file-access.integration.test.ts @@ -1204,7 +1204,7 @@ describe('#30892 — a record\'s files for a resolved caller: read one, attach o }); return call('PUT', `${BASE}/upload-links/:token`, { params: { token }, - headers: { 'content-type': 'multipart/form-data; boundary=----os', ...sessionOf(user) }, + headers: { 'content-type': 'multipart/form-data; boundary=----os', 'x-upload-link-form': 'several', ...sessionOf(user) }, body, // A transport hands the body's bytes too; a link that reads no form takes them. rawBody: async () => Buffer.from('------os--\r\n'), @@ -1215,7 +1215,7 @@ describe('#30892 — a record\'s files for a resolved caller: read one, attach o const putForm = (token: string, body: Record, headers: Record = {}) => call('PUT', `${BASE}/upload-links/:token`, { params: { token }, - headers: { 'content-type': 'multipart/form-data; boundary=----os', ...headers, ...sessionOf(OWNER.userId) }, + headers: { 'content-type': 'multipart/form-data; boundary=----os', 'x-upload-link-form': 'several', ...headers, ...sessionOf(OWNER.userId) }, body, rawBody: async () => Buffer.from('------os--\r\n'), }); @@ -1500,6 +1500,10 @@ describe('#30892 — a record\'s files for a resolved caller: read one, attach o const over = await useLink(token, raw, { 'content-type': multipart, 'content-length': String(MIB + 1) }); expect(over._status, JSON.stringify(over._json)).toBe(413); expect(over._json.error.message).toBe(uploadSizeRefusal(MIB + 1, MIB, (n) => `The upload body is ${n} bytes`)); + // So is the page's own form, header and all: such a link reads no form. + const marked = await putForm(token, { count: '1', ...countedParts(1).parts }, { 'content-length': String(MIB + 1) }); + expect(marked._status, JSON.stringify(marked._json)).toBe(413); + expect(marked._json.error.message).toBe(over._json.error.message); // The body is the file: stored as sent, its size the body's length. const res = await useLink(token, raw, { 'content-type': multipart }); expect(res._status, JSON.stringify(res._json)).toBe(200); @@ -1512,6 +1516,63 @@ describe('#30892 — a record\'s files for a resolved caller: read one, attach o } }); + it('a multipart body without the form header is the file on every link, a multi-file field\'s and a count-1 link\'s included, under the one-file limit, as before', async () => { + const multipart = 'multipart/form-data; boundary=----os'; + const raw = Buffer.from('------os\r\nContent-Disposition: form-data; name="file0"; filename="a.pdf"\r\n\r\n%PDF-1.4\r\n------os--\r\n'); + storage.setLimitsSnapshot({ maxUploadMb: { value: 1, authored: true } } as never); + try { + const record = await files.createUploadLinkAs('claim', await newClaim('raw-multipart'), { field: 'scans' }, OWNER as never); + const pre = await files.createUploadLinkForNewRecordAs('claim', { field: 'scans', count: 1 }, OWNER as never); + for (const grant of [record, pre]) { + const token = tokenOf(grant.path); + const over = await useLink(token, raw, { 'content-type': multipart, 'content-length': String(MIB + 1) }); + expect(over._status, JSON.stringify(over._json)).toBe(413); + expect(over._json.error.message).toBe(uploadSizeRefusal(MIB + 1, MIB, (n) => `The upload body is ${n} bytes`)); + // Even a body shaped like the form (`count`, `file0`) is the file when it does not say it is the form. + const res = await call('PUT', `${BASE}/upload-links/:token`, { + params: { token }, + headers: { 'content-type': multipart, 'x-file-name': encodeURIComponent('scan 1.pdf'), ...sessionOf(OWNER.userId) }, + body: { count: '1', ...countedParts(1).parts }, + rawBody: async () => raw, + }); + expect(res._status, JSON.stringify(res._json)).toBe(200); + expect(res._json.data.size).toBe(raw.length); + expect(res._json.data.fileIds).toEqual([res._json.data.fileId]); + } + } finally { + storage.setLimitsSnapshot({} as never); + } + }); + + it('a form to a link that cannot be used takes the one-file path: over the one-file limit it is refused 413 with the one-file words, as before', async () => { + const grant = await files.createUploadLinkAs('claim', ids.claimB, { field: 'policy' }, OWNER as never); + expect((await useLink(tokenOf(grant.path), Buffer.from('%PDF-1.4 used')))._status).toBe(200); + storage.setLimitsSnapshot({ maxUploadMb: { value: 1, authored: true } } as never); + try { + const over = await putForm(tokenOf(grant.path), { count: '1', ...countedParts(1).parts }, { 'content-length': String(MIB + 1) }); + expect(over._status, JSON.stringify(over._json)).toBe(413); + expect(over._json.error.message).toBe(uploadSizeRefusal(MIB + 1, MIB, (n) => `The upload body is ${n} bytes`)); + } finally { + storage.setLimitsSnapshot({} as never); + } + expect((await putForm(tokenOf(grant.path), { count: '1', ...countedParts(1).parts }))._status).toBe(404); + }); + + it('a link whose reserved ids name a file twice, or its own id, is the one unusable link', async () => { + for (const forge of ['twice', 'own'] as const) { + const grant = await files.createUploadLinkForNewRecordAs('claim', { field: 'scans', count: 3 }, OWNER as never); + const [linkId, first] = grant.fileIds; + const row = await fileRow(linkId); + const state = JSON.parse(row.metadata); + state.reserved_ids = forge === 'twice' ? `${first},${first}` : `${linkId},${first}`; + await engine.update('sys_file', { metadata: JSON.stringify(state) }, { where: { id: linkId }, context: SYS } as never); + const res = await useLinkForm(tokenOf(grant.path), [pdf(`fg-${forge}-1.pdf`), pdf(`fg-${forge}-2.pdf`), pdf(`fg-${forge}-3.pdf`)]); + expect(res._status, `${forge}: ${JSON.stringify(res._json)}`).toBe(404); + expect(res._json.error.message).toBe(UPLOAD_LINK_UNUSABLE_MESSAGE); + expect(await rowsNamed([`fg-${forge}-1.pdf`, `fg-${forge}-2.pdf`, `fg-${forge}-3.pdf`])).toEqual([]); + } + }); + it('a form on a multi-file field\'s link declares up to that link\'s files, each within the limit', async () => { storage.setLimitsSnapshot({ maxUploadMb: { value: 1, authored: true } } as never); try { @@ -1554,6 +1615,8 @@ describe('#30892 — a record\'s files for a resolved caller: read one, attach o expect(several._status).toBe(200); expect(String(several._sent)).toContain(''); expect(String(several._sent)).toContain(UPLOAD_LINK_COPY.en.wantedSeveral(UPLOAD_LINK_MAX_FILES)); + // The page's form says it is the form; nothing else is read as one. + expect(String(several._sent)).toContain('headers:{"x-upload-link-form":"several"},body:form'); const exact = await openLink(tokenOf((await files.createUploadLinkForNewRecordAs('claim', { field: 'scans', count: 3 }, OWNER as never)).path)); expect(String(exact._sent)).toContain(UPLOAD_LINK_COPY.en.wantedExactly(3)); expect(String(exact._sent)).toContain('multiple'); diff --git a/packages/services/service-storage/src/record-file-access.ts b/packages/services/service-storage/src/record-file-access.ts index f207940711f..2092378512c 100644 --- a/packages/services/service-storage/src/record-file-access.ts +++ b/packages/services/service-storage/src/record-file-access.ts @@ -166,9 +166,11 @@ import { assertFileConstraints } from './file-reference-lifecycle.js'; * as it was before this rule (to a record, the record's write judges the * field's constraints), and takes its body as the file, whatever its * content type, as it did before links took several. - * - **The several-file form** names `count`, at most the link's cap, and the - * door refuses a form whose `count` is over the link's cap or whose parts - * disagree with it before it reads any part's bytes. + * - **The several-file form** is a `multipart/form-data` body marked by + * the form header, read only on a link that takes several files; any other + * body is the file itself. It names `count`, at most the link's cap, and + * the door refuses a form whose `count` is over the link's cap or whose + * parts disagree with it before it reads any part's bytes. * - **All or nothing after the spend.** A link naming a record stores every * file, then writes the field once, appending all of them. When any store * or the write fails, every file of the submit is discarded, bytes and @@ -569,6 +571,8 @@ function openLinkStateOf(row: FileRecord | null): UploadLinkState | null { if (s.target !== 'field' || s.record_id !== undefined || typeof s.reserved_ids !== 'string') return null; const ids = s.reserved_ids.split(','); if (ids.length < 1 || ids.length >= UPLOAD_LINK_MAX_FILES || !ids.every((id) => LINK_ID.test(id))) return null; + // Each id names one file of the submit: none twice, and none the link's own. + if (new Set(ids).size !== ids.length || ids.includes(row.id)) return null; } return s as UploadLinkState; } diff --git a/packages/services/service-storage/src/storage-routes.ts b/packages/services/service-storage/src/storage-routes.ts index 03f839826ad..1a1ef946bcd 100644 --- a/packages/services/service-storage/src/storage-routes.ts +++ b/packages/services/service-storage/src/storage-routes.ts @@ -71,6 +71,8 @@ import { UPLOAD_LINK_FILE_COUNT_CODE, UPLOAD_LINK_FILE_COUNT_STATUS, UPLOAD_LINK_FORM_FILE_PREFIX, + UPLOAD_LINK_FORM_HEADER, + UPLOAD_LINK_FORM_HEADER_VALUE, UPLOAD_LINK_SEGMENT, UPLOAD_LINK_UNUSABLE_CODE, UPLOAD_LINK_UNUSABLE_MESSAGE, @@ -1887,16 +1889,17 @@ export function registerStorageFamily( // The declared length first: this door refuses a body that declares more // than it takes before this door reads it. The service judges the bytes // read again, before the link is spent, so an oversized upload never uses - // it up. [#32747] Which submit a link takes is the link's: only a link - // that takes several files reads a form (`multipart/form-data`), which - // may declare up to as many files as that link takes, each within the - // limit, plus the form's framing. A link that takes one file takes its - // body as the file, whatever its content type, under the one-file limit, - // exactly as before links took several. + // it up. [#32747] A body is the page's several-file form only when it + // says so (`multipart/form-data` carrying the form header) AND the link + // takes several files; that form may declare up to as many files as the + // link takes, each within the limit, plus the form's framing. Any other + // body, on any link, is the file itself, whatever its content type, + // under the one-file limit, with the checks and order it had before + // links took several. const token = String(req.params.token ?? ''); const { maxUploadBytes } = currentLimits(); const declaredBody = declaredContentLength(req); - const linkFiles = isUploadLinkForm(req.headers?.['content-type']) + const linkFiles = isUploadLinkForm(req.headers?.['content-type'], req.headers?.[UPLOAD_LINK_FORM_HEADER]) ? await severalFilesOf(door, token, caller.userId as string) : undefined; const formLimit = @@ -2483,10 +2486,20 @@ async function severalFilesOf( return files.max > 1 ? files : undefined; } -/** [#32747] Is the submit a several-file form (`multipart/form-data`)? */ -function isUploadLinkForm(raw: string | string[] | undefined): boolean { - const first = Array.isArray(raw) ? raw[0] : raw; - return typeof first === 'string' && first.split(';')[0].trim().toLowerCase() === 'multipart/form-data'; +/** + * [#32747] Is the submit the page's several-file form: `multipart/form-data` + * carrying {@link UPLOAD_LINK_FORM_HEADER}? A multipart body without it is a + * file, as it was before links took several. + */ +function isUploadLinkForm(contentType: string | string[] | undefined, marker: string | string[] | undefined): boolean { + const type = Array.isArray(contentType) ? contentType[0] : contentType; + const mark = Array.isArray(marker) ? marker[0] : marker; + return ( + typeof type === 'string' && + type.split(';')[0].trim().toLowerCase() === 'multipart/form-data' && + typeof mark === 'string' && + mark.trim().toLowerCase() === UPLOAD_LINK_FORM_HEADER_VALUE + ); } /** [#32747] A form value that is a file: what a form parser hands for a file part. */ diff --git a/packages/services/service-storage/src/upload-link-page.ts b/packages/services/service-storage/src/upload-link-page.ts index 6c7c0f23191..1232d77f0e1 100644 --- a/packages/services/service-storage/src/upload-link-page.ts +++ b/packages/services/service-storage/src/upload-link-page.ts @@ -4,6 +4,7 @@ import { randomBytes } from 'node:crypto'; import type { IHttpResponse } from '@objectstack/spec/contracts'; import type { UploadLinkView } from './record-file-access.js'; import { formatUploadLinkExpiry, type UploadLinkCopy } from './upload-link-copy.js'; +import { UPLOAD_LINK_FORM_HEADER, UPLOAD_LINK_FORM_HEADER_VALUE } from './upload-link-wire.js'; /** * [#30892] The page an upload link opens: one file picker that sends the @@ -89,7 +90,8 @@ function shell(copy: UploadLinkCopy, title: string, body: string, nonce: string, * The script: send the picked file to this page's own address, once. `text` * is the page's status lines in its language, and the number of files the * link takes (`min`, `max`), as a JSON literal. [#32747] More than one file - * goes as one form: `file0` … `fileN-1`, each named URI-encoded, and `count`. + * goes as one form: `file0` … `fileN-1`, each named URI-encoded, and `count`, + * marked by {@link UPLOAD_LINK_FORM_HEADER}. */ function uploadScript(text: string): string { return [ @@ -105,7 +107,7 @@ function uploadScript(text: string): string { 'var request;', 'if(T.max>1){var form=new FormData();form.append("count",String(n));', 'for(var i=0;i