@@ -12,6 +12,9 @@ import { InitiateChunkedUploadRequestSchema, UploadScopeSchema } from '@objectst
1212// [#23174] A catch-all 5xx answers through `sendServerFault`: the route's
1313// generic text on the wire, the caught error with its stack in the fault log.
1414import { sendOk , sendError , sendServerFault } from '@objectstack/types' ;
15+ // The commit door's attach arm relays the attach verb's declared refusals as
16+ // the print door relays its service's: the producer's code and status.
17+ import { declaredRefusalMessage , demotedDeclaredCode , resolveThrownHttpError } from '@objectstack/types' ;
1518// [#15999] The BRAND predicate, never `instanceof` — this error crosses package
1619// boundaries and a monorepo resolves the same module through more than one path
1720// (`src` under vitest aliases, `dist` under the published `exports`), so two
@@ -435,7 +438,8 @@ export interface StorageRoutesOptions {
435438 *
436439 * Routes:
437440 * - POST /storage/upload/presigned → get presigned upload URL
438- * - POST /storage/upload/complete → mark upload as committed
441+ * - POST /storage/upload/complete → mark upload as committed (and, with
442+ * `attachTo`, attach it to a record as the caller)
439443 * - POST /storage/upload/chunked → initiate chunked upload
440444 * - PUT /storage/upload/chunked/:uploadId/chunk/:chunkIndex → upload a chunk
441445 * - POST /storage/upload/chunked/:uploadId/complete → complete chunked
@@ -468,6 +472,60 @@ export function registerStorageRoutes(
468472 */
469473export type StorageGatedSessionReader = ( req : IHttpRequest ) => Promise < unknown > ;
470474
475+ /** What the commit door's `attachTo` names: the upload, and the record it is attached to. */
476+ export interface StorageUploadAttachment {
477+ fileId : string ;
478+ parentObject : string ;
479+ parentId : string ;
480+ eTag ?: string ;
481+ }
482+
483+ /**
484+ * Package-internal: attach the request's caller's own pending upload to a
485+ * record and commit it, as that caller — the commit door's `attachTo` arm.
486+ * Resolves the request's FULL execution context (the one request-to-context
487+ * composition, as the download authorizer does) and hands it to the
488+ * file-attachments service's caller-scoped `attachUploadAs`, which asks every
489+ * check and vouches for that one file. It throws what that verb throws, with
490+ * its declared `code` and `status`.
491+ *
492+ * Bound by `composeStorageRoutes` alone, like every other storage gate, and a
493+ * parameter of {@link registerStorageFamily} rather than a
494+ * `StorageRoutesOptions` key, so no exported declaration moves and no host can
495+ * hand the door an attacher of its own. `undefined` (no `auth` service, or no
496+ * data engine): the door refuses an `attachTo` with `501`, and a completion
497+ * without one is unchanged.
498+ */
499+ export type StorageUploadAttacher = (
500+ req : IHttpRequest ,
501+ upload : StorageUploadAttachment ,
502+ ) => Promise < { attachmentId : string } > ;
503+
504+ /** The body keys of `attachTo` — `CompleteUploadRequestSchema.attachTo` (`@objectstack/spec/api`). */
505+ const ATTACH_TO_FIELDS = [ 'parentObject' , 'parentId' ] as const ;
506+
507+ /**
508+ * The commit door's `attachTo`: `null` when the request carries none, the
509+ * target when it is well formed, or the sentence a `400` answers.
510+ */
511+ function attachTargetOf ( value : unknown ) : { parentObject : string ; parentId : string } | null | string {
512+ if ( value === undefined ) return null ;
513+ const shape =
514+ `attachTo is an object with the fields ${ ATTACH_TO_FIELDS . join ( ' and ' ) } , each a non-empty string: ` +
515+ 'the record the upload is attached to.' ;
516+ if ( value === null || typeof value !== 'object' || Array . isArray ( value ) ) return shape ;
517+ const fields = value as Record < string , unknown > ;
518+ const known = new Set < string > ( ATTACH_TO_FIELDS ) ;
519+ const unknown = Object . keys ( fields ) . filter ( ( key ) => ! known . has ( key ) ) ;
520+ if ( unknown . length > 0 ) {
521+ return `${ unknown . map ( ( k ) => `'${ k } '` ) . join ( ', ' ) } ${ unknown . length === 1 ? 'is not a field' : 'are not fields' } of attachTo. ${ shape } ` ;
522+ }
523+ const { parentObject, parentId } = fields ;
524+ if ( typeof parentObject !== 'string' || parentObject . length === 0 ) return shape ;
525+ if ( typeof parentId !== 'string' || parentId . length === 0 ) return shape ;
526+ return { parentObject, parentId } ;
527+ }
528+
471529/**
472530 * Package-internal: register the storage family through ONE door, which asks
473531 * the ADR-0069 gate before any route runs (see `mountFamilyRoute` below).
@@ -485,6 +543,7 @@ export function registerStorageFamily(
485543 store : StorageMetadataStore ,
486544 opts : StorageRoutesOptions ,
487545 readGatedSessionUser : StorageGatedSessionReader | undefined ,
546+ attachUpload : StorageUploadAttacher | undefined = undefined ,
488547) : void {
489548 const basePath = opts . basePath ?? '/api/v1/storage' ;
490549 const downloadTtl = opts . downloadTtl ?? 300 ;
@@ -1053,11 +1112,17 @@ export function registerStorageFamily(
10531112 // statement unscoped and raising `[tenant-audit]`.
10541113 const session = await requireUploadSession ( req , res ) ;
10551114 if ( session === false ) return ;
1056- const { fileId, eTag } = req . body ?? { } ;
1115+ const { fileId, eTag, attachTo } = req . body ?? { } ;
10571116 if ( ! fileId ) {
10581117 sendError ( res , 400 , 'INVALID_REQUEST' , 'fileId is required' ) ;
10591118 return ;
10601119 }
1120+ // The attach arm's target, judged before anything is read.
1121+ const attach = attachTargetOf ( attachTo ) ;
1122+ if ( typeof attach === 'string' ) {
1123+ sendError ( res , 400 , 'INVALID_REQUEST' , attach ) ;
1124+ return ;
1125+ }
10611126
10621127 const file = await store . getFile ( fileId ) ;
10631128 if ( ! file ) {
@@ -1082,6 +1147,43 @@ export function registerStorageFamily(
10821147 return ;
10831148 }
10841149
1150+ // The attach arm: the record attachments surface's attach verb. The
1151+ // commit and the `sys_attachment` insert are one unit, run as the caller
1152+ // by the file-attachments service (`attachUploadAs`), which asks the
1153+ // ownership rule again, the upload's state and scope, the permission to
1154+ // create an attachment, the parent-EDIT attach rule and the parent read,
1155+ // and vouches for this one file on its own insert — so a member who may
1156+ // attach need not read `sys_file`. ⛔ The generic data door gets no such
1157+ // mark: a `sys_attachment` create through it naming a file the caller
1158+ // cannot read is still refused `reference_not_found`.
1159+ if ( attach ) {
1160+ if ( ! attachUpload || session === null ) {
1161+ sendError (
1162+ res ,
1163+ 501 ,
1164+ 'NOT_IMPLEMENTED' ,
1165+ 'This storage mount cannot attach an upload as its caller: the kernel composes no auth service or no ' +
1166+ 'data engine. Complete the upload without attachTo.' ,
1167+ ) ;
1168+ return ;
1169+ }
1170+ let attached : { attachmentId : string } ;
1171+ try {
1172+ attached = await attachUpload ( req , {
1173+ fileId : String ( fileId ) ,
1174+ parentObject : attach . parentObject ,
1175+ parentId : attach . parentId ,
1176+ ...( eTag !== undefined && eTag !== null ? { eTag } : { } ) ,
1177+ } ) ;
1178+ } catch ( err ) {
1179+ relayAttachFailure ( res , err , `${ basePath } /upload/complete` ) ;
1180+ return ;
1181+ }
1182+ const attachedFile = ( await store . getFile ( fileId ) ) ?? file ;
1183+ sendOk ( res , { ...committedFileMetadata ( attachedFile , fileId ) , attachmentId : attached . attachmentId } ) ;
1184+ return ;
1185+ }
1186+
10851187 const updated = await store . updateFile (
10861188 fileId ,
10871189 {
@@ -1091,19 +1193,7 @@ export function registerStorageFamily(
10911193 writeContext ,
10921194 ) ;
10931195
1094- sendOk ( res , {
1095- // The opaque sys_file id — the value a file field stores as a
1096- // reference (ADR-0104 D3). Previously omitted, so a caller could not
1097- // learn the id to persist after committing an upload.
1098- fileId : updated ! . id ?? fileId ,
1099- path : updated ! . key ,
1100- name : updated ! . name ,
1101- size : updated ! . size ?? 0 ,
1102- mimeType : updated ! . mime_type ?? 'application/octet-stream' ,
1103- lastModified : updated ! . updated_at ?? new Date ( ) . toISOString ( ) ,
1104- created : updated ! . created_at ?? new Date ( ) . toISOString ( ) ,
1105- etag : updated ! . etag ,
1106- } ) ;
1196+ sendOk ( res , committedFileMetadata ( updated ! , fileId ) ) ;
11071197 } catch ( err : any ) {
11081198 sendServerFault ( res , 500 , 'INTERNAL' , 'Internal error' , err ) ;
11091199 }
@@ -1995,6 +2085,54 @@ export async function heldBytesRefusal(storage: IStorageService, file: FileRecor
19952085 ) ;
19962086}
19972087
2088+ /**
2089+ * The commit door's answer for a committed file — `FileUploadResponseSchema`'s
2090+ * `data` (`@objectstack/spec/api`).
2091+ */
2092+ function committedFileMetadata ( file : FileRecord , fileId : string ) : Record < string , unknown > {
2093+ return {
2094+ // The opaque sys_file id — the value a file field stores as a
2095+ // reference (ADR-0104 D3). Previously omitted, so a caller could not
2096+ // learn the id to persist after committing an upload.
2097+ fileId : file . id ?? fileId ,
2098+ path : file . key ,
2099+ name : file . name ,
2100+ size : file . size ?? 0 ,
2101+ mimeType : file . mime_type ?? 'application/octet-stream' ,
2102+ lastModified : file . updated_at ?? new Date ( ) . toISOString ( ) ,
2103+ created : file . created_at ?? new Date ( ) . toISOString ( ) ,
2104+ etag : file . etag ,
2105+ } ;
2106+ }
2107+
2108+ /**
2109+ * The commit door's relay for a refused or failed attach: a declared `4xx` —
2110+ * the attach verb's own refusals, the `sys_attachment` insert's gates (the
2111+ * permission to create, `ATTACHMENT_PARENT_ACCESS`, `FILES_DISABLED`, a
2112+ * `VALIDATION_FAILED` with its field details) — keeps its code, status,
2113+ * message and details; a declared `5xx` keeps its code and status with this
2114+ * door's generic text unless the producer declared the text for its caller;
2115+ * anything else is a fault.
2116+ */
2117+ function relayAttachFailure ( res : IHttpResponse , err : unknown , path : string ) : void {
2118+ const thrown = resolveThrownHttpError ( err , 500 ) ;
2119+ if ( thrown . status < 500 ) {
2120+ const declaredCode = demotedDeclaredCode ( thrown ) ;
2121+ sendError ( res , thrown . status , thrown . code , thrown . message , {
2122+ ...( thrown . details ? { details : thrown . details } : { } ) ,
2123+ ...( declaredCode !== undefined ? { declaredCode } : { } ) ,
2124+ ...( thrown . userMessage !== undefined ? { userMessage : thrown . userMessage } : { } ) ,
2125+ } ) ;
2126+ return ;
2127+ }
2128+ const refusal = declaredRefusalMessage ( err ) ;
2129+ if ( refusal !== undefined ) {
2130+ sendError ( res , thrown . status , thrown . code , refusal ) ;
2131+ return ;
2132+ }
2133+ sendServerFault ( res , thrown . status , thrown . code , 'Internal error' , err , { method : 'POST' , path } ) ;
2134+ }
2135+
19982136/**
19992137 * [#24548] Whether a local adapter read failed because no file is stored under
20002138 * the key: Node's `ENOENT`, which `LocalStorageAdapter.download` passes through
0 commit comments