Changelog - 2026-09-25
Static asset component
New Feature Feature Fix Enhancement Breaking Deprecation Behavior Change Bug FixIn one line. The static-asset component can serve one bucket, scope a shared bucket, accept browser uploads straight to storage and keep MetaLink rows ordered and fresh, and a few names, codes and shapes changed on the way.
What changed
Routes and options
controller.bucketpins one bucket (a string or a resolver) and removes/buckets/{bucketName}fromupload,listObjects,getObjectByName,downloadObjectByName,deleteObjectandrecreateMetaLink, and from the generatedlink.getBuckets,getBucketByName,createBucketanddeleteBucketare not registered and answer 404.buildAssetDefinitions({ hasConfiguredBucket, rawObjectPath })builds the route configs;StaticAssetDefinitionskeeps its value.controller.rawObjectPath: trueservesphotos/2024/f.jpgraw as well as percent-encoded, so stored links keep working. Default isfalse, which keeps today's paths. Validation,maxFolderDepthincluded, runs on the joined path. A catch-all matches everything under its prefix and built-in routes register first, so usedefineRoutesBeforeto put your own literal route (such as/objects/i18n) ahead of them.controller.keyPrefixconfines every route of a controller to a prefix, so two controllers or tenants can share a bucket. A key outside it answers404 core.storage.object_not_foundbefore any storage call.listObjectsnarrows a widerprefixand returns[]for a disjoint one.uploadplaces its default key under the prefix; aresolveObjectNameorextra.normalizeNameFnkey outside it is refused with400 core.static_asset.object_key_out_of_scope. Direct upload's pending key and policy carry the prefix, and the commit re-checks it.maxFolderDepthcounts below the prefix. With neither hook set, the default naming keeps the original file name to one segment, so a/in it is400 [upload] Invalid original file name.keyPrefixrequirescontroller.bucketand throws at registration without it.defineRoutesBeforeanddefineExtraRoutesare not scoped.routes.<key>.enabled: falsedrops a built-in route entirely (no path, no OpenAPI entry), the same switch the CRUD controller factory uses.resolveObjectNamedecides the stored object name; it is offered the original name, the default name IGNIS would have written, and the bucket. The result is still checked withisValidPath().defineExtraRoutesregisters your routes after the built-in ones, which win a path collision. Both pass through the component config.maxBytes(extra.maxBytes) caps the upload route. Over the ceiling answers413withcore.static_asset.upload_too_large. The declaredcontent-lengthis checked before the body is spooled, then each file'sbuffer.lengthafter parsing. The check runs after your ownroutes.upload.middleware, so your own size guard still answers first. It only bounds a declaredcontent-length; a chunked request skips it, so pair it withconfigs.middlewares.bodyLimit.presignPutaccepts an optionalcontentTypeand signs it, so the URL holder cannot choose the stored type. Omit it and the URL signs what it signed before.getBaseWhere(in@venizia/ignis-kernel): overrideReadableCrudController.getBaseWhere({ context })to scope every read verb of a CRUD controller, replacing overrides offindandcount. Each verb ANDs it into the request filter;findByIdgoes throughrepository.findOne, and an id outside the scope answers{ count: 0, data: null }. It is public, not protected. Write the scope to fail closed. Only read verbs call it;create,updateById,deleteByIdanddeleteBydo not.
class OrderController extends ControllerFactory.defineCrudController({ ... }) {
override async getBaseWhere(opts: { context: TRouteContext }) {
const tenantId = opts.context.req.header('x-tenant-id');
return { tenantId: tenantId ?? null };
}
}Direct upload
Configure controller.directUpload and two routes appear, so the bytes never pass through IGNIS:
POST {base}/upload-policy { files: [{ fileName, contentType, size }] }
-> [{ postURL, formData, objectName, commitToken, expiresAt }]
POST {base}/upload-commit { commitToken } -> the object at its final keydirectUpload: {
authorize: ({ context }) => Boolean(context.get('currentUser')),
secretKey: process.env.APP_ENV_UPLOAD_SECRET,
maxBytes: 100 * 1024 * 1024,
}authorizeis required.controller.bucketmust also be set.- A POST policy, not a presigned PUT, because only a policy can express a ceiling (
content-length-range). - The commit is claimed with a signed token, never a key. It is verified before any storage call, so a forged token costs nothing to reject and reveals nothing. The token carries no business fields.
- The final key is never inside a policy. A policy authorizes only
pending/<generated>; commit copies server-side to the final key and removes the temporary object, so content cannot be replaced after commit. If removing the temporary object fails, the commit still succeeds and logs a warning; use a lifecycle rule on the pending prefix.onCommitruns before the copy. upload-commitwrites a MetaLink row, through the same builder as the ordinary upload, and takes the same labels. A row failure answers 200 with{ "metaLink": { "error": "META_LINK_CREATE_FAILED" } }, because the object is already committed.metaLink({ data }or{ error }) is in the OpenAPI schema.- Not built: multipart or resumable upload, and malware scanning (
onCommitis the seam).
MetaLink
- Your own table.
TStaticAssetsComponentOptionsandStaticAssetComponenttake the MetaLink table as a type argument, constrained byTMetaLinkCompatibleSchema(any table whose row has the MetaLink fields). A table in another Postgres schema or with another name now type-checks, so drop anyas unknown as TMetaLinkConfig['model']cast. A table missing a field is still refused. A column you add yourself must be nullable or have a default.createMetaLinkis typed as returning{ count: number; data: TTableObject<Schema> }. PUT .../meta-links/{objectName}refreshes every row for that object. It updatesmimetype,size,etagandisSynced: true, and leaves each row'sstorageType,variant,principalType,principalIdandsequencealone. It creates a row (through yourcreateMetaLinkhook and the upload builder) only when none existed. The response gainsaction('refreshed' | 'created'),countandmetaLinks;successandmetaLink(nowmetaLinks[0]) keep their shape.- With a
metaLink.createMetaLinkhook, a refresh leaveslinkandmetadataalone, so your enrichment survives. Without a hook, it refresheslinkand the stat columns, then merges each row'smetadatawith the stat's (the stat's keys win). That merge is a read-then-write, so a concurrent write to the row'smetadatacan be lost. - No unique constraint on
(bucketName, objectName), on purpose: one image can belong to a product and its variants. Refresh-then-create is therefore not atomic, and two concurrent calls on an object with no row can both create one. MetaLink.sequence(integer().notNull().default(0)) orders the rows of one principal. The caller supplies it as a form field (sequence), or in the JSON body onupload-commit. The component never derives it, because reading a maximum and writing max+1 is not atomic. Always tiebreak oncreated_at:
SELECT link FROM "MetaLink"
WHERE principal_type = 'ProductVariant' AND principal_id = $1
ORDER BY sequence, created_at;Fixes
configs.middlewares.bodyLimitis applied. It was a type nothing read. It is installed right after the request id, ahead of every other middleware. Over the limit answers413 core.request.body_too_large(or your ownonError). A missingenablestill applies the limit. AmaxSizethat is not a finite non-negative number throws at boot.compress,cors,csrfandipRestrictionare still types only. Raiseconfigs.server.maxRequestBodySizeabovebodyLimit.maxSize, or Bun's own limit answers first without the IGNIS envelope. KeepbodyLimit.pathoff a route that streams a body, because the limiter buffers the whole body.- The request spy parses forms only in development. Elsewhere it parses only
application/json. A route declaringmultipart/form-dataorapplication/x-www-form-urlencodedgets aformBodyReadermiddleware that maps a malformed form to400 core.request.body_malformed.readFormBody({ req })is new in@venizia/ignis-helpers(and/core);parseMultipartBodyuses it. - The error envelope honors a thrown
HTTPException's.status. A 4xx renders as its own status and message instead of500 core.system_error; malformed JSON on any JSON-body route is now400 Malformed JSON in request body. A 5xx stays an unexpected500with no message for the client. A raw runtime error such as aTypeErroris still500. - Non-ASCII and unusual file names work.
BunS3Helper.copyObjectencodes the copy source, so a direct-upload commit with a name likeKiểm kê.xlsxno longer fails, and keys with+,%,?or#no longer risk copying the wrong object. When a naming hook decides the key (normalizeNameFn,resolveObjectName, orcontroller.keyPrefix), names with& # ! [ ] { } ;or a leading dot are accepted; control characters, an empty name and more than 255 characters are still refused. Every key in a batch is checked before the first write.MinioHelperRFC 2047-encodesoriginalNameandnormalizeNamemetadata outside printable ASCII.createContentDispositionHeaderkeeps the real name infilename*, replacing control, bidi-override and other format characters with_except the zero-width joiner and non-joiner; thefilenamefallback stays printable ASCII. - Office types resolve in
ContentTypeTable:.xlsx,.xls,.docx,.doc,.pptx,.ppt,.odt,.ods. This changes the recorded MIME type (MetaLinkmimetype,DiskHelper.getStat,writeStream's default,AssetIngest). The servedContent-Typeis stillapplication/octet-streamwithContent-Disposition: attachment. presignPostwithvirtualHostedStyle: truenow returnshttps://<bucket>.<host>instead of repeating the bucket in the path. Path-style is unchanged.
Who is affected
- Applications that copied the asset controller to change URLs, names or routes. Delete the copy and use the options above.
- Applications that set
bucket. Move bucket creation out of the HTTP layer; those four routes are gone. - Applications that named
TResolveObjectName, branched onupload-policy's 400, called/downloads/..., callparseMultipartBodydirectly, or keep their own MetaLink table. See Breaking changes. - Applications that assign
configs.middlewares.bodyLimitinstaticConfigure()or a later hook. It is read insideregisterDefaultMiddlewares(), beforestaticConfigure(). Passmiddlewaresthrough the constructorconfig; a later assignment has no effect and the application refuses to boot when it detects the change. - Code that calls
context.req.formData()itself, ahead of any framework reader. A malformed body there is a500in production. CallreadFormBody({ req: context.req })instead; it returns the same cachedFormData. - Code that matched
statusCode: 500for a thrownHTTPException, or the old text[upload] Invalid original file namefor a name copied into a generated key (now[upload] Invalid normalized object name | name: ...). Match the new status or text. - Callers of the recreate route on a table with several rows per object. Read
metaLinks. A refresh now keeps each row's ownstorageType. - Everyone else. No action needed; the new options are optional and unset keeps today's behavior.
Breaking changes
WARNING
The renames, shapes and status codes below can stop a build or change what a client sees.
| Before | After |
|---|---|
TResolveObjectName | TObjectNameResolver |
controller.bucket?: string | (() => string) | controller.bucket?: TValueOrAsyncResolver<string> |
metaLink.model: typeof BaseRelationalEntity<Schema> | metaLink.model: TValueOrAsyncResolver<...> |
metaLink.repository: DefaultCRUDRepository<Schema> | metaLink.repository: TValueOrAsyncResolver<...> |
GET {base}/downloads/{objectName} | GET {base}/download/{objectName} |
core.static_asset.upload_too_large answers 400 (policy path only) | answers 413 on both upload paths |
const files = await parseMultipartBody({ context }) | const { files, fields } = await parseMultipartBody({ context }) |
- Resolvers. A resolver is read when the value is used, so a repository can be named before the container binds it and a bucket can come from an environment variable per request. A plain value still works, and a class is a value, never a factory. The route table type is now also exported as
TStaticAssetRoutes. - Download route. A client on the old path gets a
404at runtime, with no compile error. If you are on0.2.0-31, drop thes. To pin the path yourself, an override wins over both spellings:routes: { downloadObjectByName: { path: '/download/{objectName}{.+}' } }. The route keydownloadObjectByNameis unchanged. This reverses one row of the 2026-09-08 rename. - Too-large code. If you branch on the status from
upload-policy, branch on413. parseMultipartBodyused to drop every non-file field. It now returns{ files, fields }.MetaLink.sequence. On the shipped MetaLink table the column appears and there is nothing to write. With your own table,TMetaLinkCompatibleSchemafails to compile until you add it. Migrate both together:
ALTER TABLE "MetaLink" ADD COLUMN sequence integer NOT NULL DEFAULT 0;
CREATE INDEX "IDX_MetaLink_principal_sequence"
ON "MetaLink" (principal_type, principal_id, sequence);Upload labels move to the body
principalType, principalId, variant, sequence and folderPath leave the query string, because a query string lands in every access log on the way. Send them as form fields beside the file, and on upload-commit in the JSON body beside the token.
Before
POST {base}/objects?principalType=Product&principalId=42&folderPath=photos/2024After
const form = new FormData();
form.append('files', file);
form.append('principalType', 'Product');
form.append('principalId', '42');
form.append('folderPath', 'photos/2024');{ "commitToken": "...", "principalType": "Product", "principalId": "42", "sequence": 3 }- The query still works for now. A label left in the query is read, the body wins when both carry one, and a warning names the labels still coming from the query. The fallback will go. It stays because a form library that only emits the three-argument
append(key, value, filename)cannot put a text field in a multipart body. Move your labels when you can. folderPathis validated after the body is parsed, not before.createMetaLinkstill receives the labels asquery; the name is historical.- Omit the labels and the row is still written, unlabelled.