@venizia/ignis 0.4.8-11 → 0.4.8-13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/dist/esm/components/mail/common/types/queue.d.ts +8 -4
  2. package/dist/esm/components/mail/common/types/queue.js.map +1 -1
  3. package/dist/esm/components/mail/helpers/executors/bull-mq-executor.helper.d.ts +1 -1
  4. package/dist/esm/components/mail/helpers/executors/bull-mq-executor.helper.js +2 -16
  5. package/dist/esm/components/mail/helpers/executors/bull-mq-executor.helper.js.map +1 -1
  6. package/dist/esm/components/static-asset/common/constants.d.ts +25 -11
  7. package/dist/esm/components/static-asset/common/constants.js +40 -20
  8. package/dist/esm/components/static-asset/common/constants.js.map +1 -1
  9. package/dist/esm/components/static-asset/common/errors.d.ts +16 -39
  10. package/dist/esm/components/static-asset/common/errors.js +16 -36
  11. package/dist/esm/components/static-asset/common/errors.js.map +1 -1
  12. package/dist/esm/components/static-asset/common/index.d.ts +1 -0
  13. package/dist/esm/components/static-asset/common/index.js +1 -0
  14. package/dist/esm/components/static-asset/common/index.js.map +1 -1
  15. package/dist/esm/components/static-asset/common/keys.d.ts +1 -1
  16. package/dist/esm/components/static-asset/common/keys.js +1 -1
  17. package/dist/esm/components/static-asset/common/keys.js.map +1 -1
  18. package/dist/esm/components/static-asset/common/types.d.ts +203 -140
  19. package/dist/esm/components/static-asset/common/types.js.map +1 -1
  20. package/dist/esm/components/static-asset/common/validation.d.ts +10 -0
  21. package/dist/esm/components/static-asset/common/validation.js +8 -0
  22. package/dist/esm/components/static-asset/common/validation.js.map +1 -0
  23. package/dist/esm/components/static-asset/component.d.ts +1 -1
  24. package/dist/esm/components/static-asset/component.js +13 -55
  25. package/dist/esm/components/static-asset/component.js.map +1 -1
  26. package/dist/esm/components/static-asset/controller/factory.d.ts +185 -67
  27. package/dist/esm/components/static-asset/controller/factory.js +32 -821
  28. package/dist/esm/components/static-asset/controller/factory.js.map +1 -1
  29. package/dist/esm/components/static-asset/controller/routes/context.d.ts +61 -0
  30. package/dist/esm/components/static-asset/controller/routes/context.js +45 -0
  31. package/dist/esm/components/static-asset/controller/routes/context.js.map +1 -0
  32. package/dist/esm/components/static-asset/controller/routes/definition.d.ts +40 -0
  33. package/dist/esm/components/static-asset/controller/routes/definition.js +74 -0
  34. package/dist/esm/components/static-asset/controller/routes/definition.js.map +1 -0
  35. package/dist/esm/components/static-asset/controller/routes/direct-upload.d.ts +3 -0
  36. package/dist/esm/components/static-asset/controller/routes/direct-upload.js +131 -0
  37. package/dist/esm/components/static-asset/controller/routes/direct-upload.js.map +1 -0
  38. package/dist/esm/components/static-asset/controller/routes/labels.d.ts +16 -0
  39. package/dist/esm/components/static-asset/controller/routes/labels.js +19 -0
  40. package/dist/esm/components/static-asset/controller/routes/labels.js.map +1 -0
  41. package/dist/esm/components/static-asset/controller/routes/objects.d.ts +7 -0
  42. package/dist/esm/components/static-asset/controller/routes/objects.js +193 -0
  43. package/dist/esm/components/static-asset/controller/routes/objects.js.map +1 -0
  44. package/dist/esm/components/static-asset/controller/routes/serve.d.ts +17 -0
  45. package/dist/esm/components/static-asset/controller/routes/serve.js +127 -0
  46. package/dist/esm/components/static-asset/controller/routes/serve.js.map +1 -0
  47. package/dist/esm/components/static-asset/controller/routes/table.d.ts +12 -0
  48. package/dist/esm/components/static-asset/controller/routes/table.js +52 -0
  49. package/dist/esm/components/static-asset/controller/routes/table.js.map +1 -0
  50. package/dist/esm/components/static-asset/controller/routes/upload.d.ts +10 -0
  51. package/dist/esm/components/static-asset/controller/routes/upload.js +174 -0
  52. package/dist/esm/components/static-asset/controller/routes/upload.js.map +1 -0
  53. package/dist/esm/components/static-asset/models/base.model.d.ts +4 -4
  54. package/dist/esm/components/static-asset/models/base.model.js.map +1 -1
  55. package/dist/esm/components/static-asset/services/commitment.service.d.ts +53 -16
  56. package/dist/esm/components/static-asset/services/commitment.service.js +114 -35
  57. package/dist/esm/components/static-asset/services/commitment.service.js.map +1 -1
  58. package/dist/esm/components/static-asset/services/policy.service.d.ts +7 -3
  59. package/dist/esm/components/static-asset/services/policy.service.js +29 -7
  60. package/dist/esm/components/static-asset/services/policy.service.js.map +1 -1
  61. package/dist/esm/components/static-asset/utilities/commit-token.utility.d.ts +5 -1
  62. package/dist/esm/components/static-asset/utilities/commit-token.utility.js +58 -2
  63. package/dist/esm/components/static-asset/utilities/commit-token.utility.js.map +1 -1
  64. package/dist/esm/components/static-asset/utilities/entry.utility.d.ts +69 -0
  65. package/dist/esm/components/static-asset/utilities/entry.utility.js +153 -0
  66. package/dist/esm/components/static-asset/utilities/entry.utility.js.map +1 -0
  67. package/dist/esm/components/static-asset/utilities/index.d.ts +3 -0
  68. package/dist/esm/components/static-asset/utilities/index.js +3 -0
  69. package/dist/esm/components/static-asset/utilities/index.js.map +1 -1
  70. package/dist/esm/components/static-asset/utilities/ingest.utility.js +2 -4
  71. package/dist/esm/components/static-asset/utilities/ingest.utility.js.map +1 -1
  72. package/dist/esm/components/static-asset/utilities/key-scope.utility.d.ts +6 -2
  73. package/dist/esm/components/static-asset/utilities/key-scope.utility.js +24 -6
  74. package/dist/esm/components/static-asset/utilities/key-scope.utility.js.map +1 -1
  75. package/dist/esm/components/static-asset/utilities/meta-link.utility.d.ts +2 -2
  76. package/dist/esm/components/static-asset/utilities/meta-link.utility.js +6 -6
  77. package/dist/esm/components/static-asset/utilities/meta-link.utility.js.map +1 -1
  78. package/dist/esm/components/static-asset/utilities/object-link.utility.d.ts +2 -2
  79. package/dist/esm/components/static-asset/utilities/object-link.utility.js +4 -5
  80. package/dist/esm/components/static-asset/utilities/object-link.utility.js.map +1 -1
  81. package/dist/esm/components/static-asset/utilities/pinned-file.utility.d.ts +39 -0
  82. package/dist/esm/components/static-asset/utilities/pinned-file.utility.js +53 -0
  83. package/dist/esm/components/static-asset/utilities/pinned-file.utility.js.map +1 -0
  84. package/dist/esm/components/static-asset/utilities/route-options.utility.d.ts +20 -5
  85. package/dist/esm/components/static-asset/utilities/route-options.utility.js +44 -6
  86. package/dist/esm/components/static-asset/utilities/route-options.utility.js.map +1 -1
  87. package/dist/esm/components/static-asset/utilities/toggle.utility.d.ts +13 -0
  88. package/dist/esm/components/static-asset/utilities/toggle.utility.js +16 -0
  89. package/dist/esm/components/static-asset/utilities/toggle.utility.js.map +1 -0
  90. package/dist/presets/app/preset.json +4 -4
  91. package/dist/presets/lib/preset.json +3 -3
  92. package/dist/presets/shared/preset.json +1 -1
  93. package/package.json +6 -6
  94. package/dist/esm/components/static-asset/controller/base.definition.d.ts +0 -30
  95. package/dist/esm/components/static-asset/controller/base.definition.js +0 -307
  96. package/dist/esm/components/static-asset/controller/base.definition.js.map +0 -1
@@ -9,845 +9,56 @@ var __metadata = (this && this.__metadata) || function (k, v) {
9
9
  };
10
10
  import { BaseRestController } from '../../../base/controllers/index.js';
11
11
  import { controller as controllerDecorator } from '../../../base/metadata/index.js';
12
- import { BaseStorageHelper, RequestUtility, StorageUtility, } from '@venizia/ignis-helpers';
13
- import { HTTP, ResolverUtility } from '@venizia/ignis-helpers/common';
14
- import { BaseHelper, getError } from '@venizia/ignis-helpers/core';
15
- import { readFileSync, rmSync } from 'node:fs';
16
- import { StaticAssetContentTypes, StaticAssetErrors, StaticAssetMetaLinkCodes, StaticAssetHeaders, } from '../common/index.js';
17
- import { StaticAssetDefaults, MetaLinkRecreateActions } from '../common/index.js';
18
- import { StaticAssetDefinitionBuilder } from './base.definition.js';
19
- import { StaticAssetKeyScopeUtility } from '../utilities/key-scope.utility.js';
20
- import { StaticAssetMetaLinkUtility } from '../utilities/meta-link.utility.js';
21
- import { StaticAssetObjectLinkUtility } from '../utilities/object-link.utility.js';
22
- import { StaticAssetRouteOptionsUtility } from '../utilities/route-options.utility.js';
23
- /** Hono ALREADY percent-decodes path params - a second decodeURIComponent throws on `report_100%.pdf` and turns `a%2Fb.png` into a DIFFERENT object; `isValidName`/`isValidPath` still run on this value, so traversal is still rejected. */
24
- /** The upload labels, read off the multipart form. Every value arrives as text, so `sequence` is the one that needs converting. */
25
- /** One list: the reader below and the stale-caller warning must agree. */
26
- const UPLOAD_LABEL_NAMES = [
27
- 'principalType',
28
- 'principalId',
29
- 'variant',
30
- 'sequence',
31
- 'folderPath',
32
- ];
33
- /** The body of `StaticAssetControllerFactory.findLabelsInQuery`, callable from the helpers above the class. */
34
- const listLabelsInQuery = (opts) => (opts.names ?? UPLOAD_LABEL_NAMES).filter((name) => opts.query[name] !== undefined);
35
- /** Refused before the body is read: a route that ignored them would store an unlabelled row. */
36
- const refuseLabelsInQuery = (opts) => {
37
- const names = listLabelsInQuery(opts);
38
- if (names.length > 0) {
39
- throw getError({
40
- error: StaticAssetErrors.LABELS_IN_QUERY,
41
- message: `${opts.reason ?? 'Upload labels belong in the request body, not the query'} | names: ${names.join(', ')}`,
42
- });
43
- }
44
- };
45
- /** The commit body carries four of the five: the object key - and so `folderPath` - was fixed when the policy was issued. */
46
- const COMMIT_LABEL_NAMES = UPLOAD_LABEL_NAMES.filter((name) => name !== 'folderPath');
47
- // A multipart form hands strings; a JSON commit body may hand `sequence` as a number.
48
- const readUploadLabels = (opts) => {
49
- const { fields } = opts;
50
- const read = (name) => {
51
- const value = fields[name];
52
- return value === undefined || value === '' ? undefined : String(value);
53
- };
54
- const sequence = read('sequence');
55
- return {
56
- principalType: read('principalType'),
57
- principalId: read('principalId'),
58
- variant: read('variant'),
59
- sequence: sequence === undefined ? undefined : Number(sequence),
60
- folderPath: read('folderPath'),
61
- };
62
- };
63
- const readObjectName = (rawObjectName) => rawObjectName;
64
- /** The bucket one request works on: a configured value wins - called on every request, so an application may read an environment variable lazily - else the path param, which is only registered when there is no configured bucket. */
65
- const resolveBucket = async (opts) => {
66
- const { configured, param } = opts;
67
- if (configured === undefined) {
68
- return param ?? '';
69
- }
70
- return ResolverUtility.resolveValueAsync({ value: configured });
71
- };
72
- /** Mirrors `BaseStorageHelper.normalizeObjectName`, which is protected: `resolveObjectName` is offered the very name the helper would otherwise have written. */
73
- const defaultObjectName = ({ file }) => {
74
- const { originalName, folderPath } = file;
75
- const normalizedFileName = originalName.toLowerCase().replace(/ /g, '_');
76
- if (!folderPath) {
77
- return normalizedFileName;
78
- }
79
- return `${folderPath.toLowerCase().replace(/ /g, '_')}/${normalizedFileName}`;
80
- };
81
- /**
82
- * Reads one `Range` header. Only a single byte range is honoured - multipart ranges need a multipart
83
- * body no browser asks for here. An unsatisfiable or malformed range returns `null`, and the caller
84
- * serves the whole object, which is what RFC 9110 allows.
85
- */
86
- const readByteRange = (opts) => {
87
- const { header, size } = opts;
88
- if (!header || size <= 0) {
89
- return null;
90
- }
91
- const match = /^bytes=(\d*)-(\d*)$/.exec(header.trim());
92
- if (!match) {
93
- return null;
94
- }
95
- const [, rawStart, rawEnd] = match;
96
- // `bytes=-500` means the LAST 500 bytes, not "from 0 to 500".
97
- if (!rawStart) {
98
- const suffixLength = Number(rawEnd);
99
- if (!Number.isInteger(suffixLength) || suffixLength <= 0) {
100
- return null;
101
- }
102
- return { start: Math.max(size - suffixLength, 0), end: size - 1 };
103
- }
104
- const start = Number(rawStart);
105
- const end = rawEnd ? Number(rawEnd) : size - 1;
106
- if (!Number.isInteger(start) || !Number.isInteger(end) || start > end || start >= size) {
107
- return null;
108
- }
109
- return { start, end: Math.min(end, size - 1) };
110
- };
111
- /** Sets whitelisted metadata headers on the response context. `content-type` is not among them. */
112
- const applyMetadataHeaders = ({ ctx, metadata }) => {
113
- Object.entries(metadata).forEach(([key, value]) => {
114
- if (!StaticAssetHeaders.ALLOWED.includes(key.toLowerCase())) {
115
- return;
116
- }
117
- ctx.header(key.toLowerCase(), String(value).replace(/[\r\n]/g, ''));
118
- });
119
- };
120
- /** Builds the REST controller class for a static asset entry. Static helpers also expose label checking, object link building and served content type resolution. */
121
- export class StaticAssetControllerFactory extends BaseHelper {
122
- constructor() {
123
- super({ scope: StaticAssetControllerFactory.name });
124
- }
125
- /** Names any label a caller put in the query - where the upload routes refuse it. */
126
- static findLabelsInQuery(opts) {
127
- return listLabelsInQuery(opts);
128
- }
129
- /** The URL of one object, in the shape its controller serves: no `/buckets/<name>` with a configured bucket, and a raw path with `rawObjectPath`. */
130
- static buildObjectLink(opts) {
131
- return StaticAssetObjectLinkUtility.build(opts);
132
- }
12
+ import { getError } from '@venizia/ignis-helpers/core';
13
+ import { StaticAssetEntryUtility, } from '../utilities/entry.utility.js';
14
+ import { StaticAssetServe } from './routes/serve.js';
15
+ import { StaticAssetRouteTable } from './routes/table.js';
16
+ /** Builds the REST controller class for a static asset entry, and decides the served content type. */
17
+ export class StaticAssetControllerFactory {
133
18
  /**
134
19
  * The served type comes from the object NAME, never the backend or the uploader: a renderable type on
135
20
  * the API origin is stored XSS. Public so a hand-written route makes the same decision - the
136
21
  * backend's own content-type is dropped by `StaticAssetHeaders.ALLOWED`.
137
22
  */
138
23
  static resolveServedContentType(opts) {
139
- const { helper, object } = opts;
140
- const candidate = helper
141
- .getMimeType({ filename: object.key })
142
- .toLowerCase()
143
- .split(';')[0]
144
- .trim();
145
- if (!StaticAssetContentTypes.RENDERABLE.has(candidate)) {
146
- return { contentType: HTTP.HeaderValues.APPLICATION_OCTET_STREAM, isRenderable: false };
147
- }
148
- return { contentType: candidate, isRenderable: true };
24
+ return StaticAssetServe.resolveServedContentType(opts);
149
25
  }
26
+ /** Resolves the entry, then builds its controller. A caller that already holds the resolved entry uses `buildResolved`. */
150
27
  static build(opts) {
151
- const { controller, helper, options, useMetaLink, metaLink, storage } = opts;
152
- const { resolveObjectName, defineRoutesBefore, defineExtraRoutes } = opts;
153
- const { directUpload } = controller;
154
- const { name, basePath, routes, isStrict = true, bucket, rawObjectPath = false } = controller;
155
- const maxFolderDepth = options?.maxFolderDepth ?? BaseStorageHelper.DEFAULT_MAX_FOLDER_DEPTH;
156
- const maxBytes = options?.maxBytes;
157
- const hasConfiguredBucket = bucket !== undefined;
158
- // With the bucket in the URL, the bucket routes stay unscoped and the scope spans every bucket.
159
- if (controller.keyPrefix !== undefined && !hasConfiguredBucket) {
28
+ return StaticAssetControllerFactory.buildResolved({
29
+ resolved: StaticAssetEntryUtility.resolve({ key: opts.key, entry: opts.entry }),
30
+ policyService: opts.policyService,
31
+ commitService: opts.commitService,
32
+ });
33
+ }
34
+ static buildResolved(opts) {
35
+ const { policyService, commitService } = opts;
36
+ const { directUpload, ...resolved } = opts.resolved;
37
+ const { name, basePath, helper, extend } = resolved;
38
+ if (directUpload && (!policyService || !commitService)) {
160
39
  throw getError({
161
- message: `[${name}] keyPrefix needs controller.bucket | a bucket in the URL is a bucket the caller chooses, and the bucket routes cannot be scoped`,
40
+ message: `[${name}] directUpload needs policyService and commitService | the component builds and binds them; a caller of StaticAssetControllerFactory.build passes its own`,
162
41
  });
163
42
  }
164
- const scope = controller.keyPrefix === undefined
165
- ? undefined
166
- : StaticAssetKeyScopeUtility.normalizePrefix({
167
- keyPrefix: controller.keyPrefix,
168
- helper,
169
- scope: name,
170
- });
171
- const keyPrefix = scope?.keyPrefix;
172
- // `maxFolderDepth` counts the caller's folders; the scope's own are configuration, not input.
173
- const objectKeyMaxDepth = maxFolderDepth + (scope?.depth ?? 0);
174
- // The component's own name under a scope: the original name must stay one segment, as without one.
175
- const isScopedDefaultNaming = keyPrefix !== undefined && !resolveObjectName && !options?.normalizeNameFn;
176
- const definitions = StaticAssetDefinitionBuilder.build({
177
- hasConfiguredBucket,
178
- rawObjectPath,
179
- maxPolicyFiles: options?.parseMultipartBody?.maxFiles ?? StaticAssetDefaults.MAX_UPLOAD_FILES,
180
- });
181
- // The mount path may be declared with or without a leading slash; a link must carry exactly one.
182
- const normalizedBasePath = StaticAssetObjectLinkUtility.normalizeBasePath({ basePath });
183
- /** Only when the URL shape deviates: with neither option the storage helper's own link is left untouched. */
184
- const shapedLinkFn = hasConfiguredBucket || rawObjectPath
185
- ? (linkOptions) => StaticAssetControllerFactory.buildObjectLink({
186
- basePath: normalizedBasePath,
187
- bucket: linkOptions.bucket,
188
- object: linkOptions.object,
189
- hasConfiguredBucket,
190
- rawObjectPath,
191
- })
192
- : undefined;
193
- const normalizeLinkFn = options?.normalizeLinkFn ?? shapedLinkFn;
43
+ const env = {
44
+ ...resolved,
45
+ directUpload: directUpload &&
46
+ policyService &&
47
+ commitService && { ...directUpload, policyService, commitService },
48
+ };
194
49
  let GeneratedStaticAssetController = class GeneratedStaticAssetController extends BaseRestController {
195
50
  constructor() {
196
- super({
197
- scope: name,
198
- path: basePath,
199
- isStrict,
200
- });
201
- }
202
- /** Clears the multipart spool files written by `parseMultipartBody({ storage: 'disk' })`. */
203
- removeSpoolFiles(spoolOptions) {
204
- for (const filePath of spoolOptions.paths) {
205
- try {
206
- rmSync(filePath, { force: true });
207
- }
208
- catch (error) {
209
- this.logger
210
- .for('UPLOAD')
211
- .error('Failed to remove spool file | path: %s | Error: %s', filePath, error);
212
- }
213
- }
51
+ super({ scope: name, path: basePath });
214
52
  }
215
53
  binding() {
216
54
  // First, so a literal path can win over the built-in catch-all `rawObjectPath` registers.
217
- defineRoutesBefore?.({ controller: this, helper, basePath: normalizedBasePath });
218
- // A single-bucket application has no reason to expose bucket creation or deletion, so the
219
- // four bucket-management routes are not registered once `bucket` is configured.
220
- if (!hasConfiguredBucket) {
221
- const getBucketsRoute = StaticAssetRouteOptionsUtility.readOverride({
222
- route: routes?.getBuckets,
223
- });
224
- if (getBucketsRoute.isEnabled) {
225
- this.bindRoute({
226
- configs: { ...definitions.GET_BUCKETS, ...getBucketsRoute.override },
227
- }).to({
228
- handler: async (ctx) => {
229
- const buckets = await helper.getBuckets();
230
- return ctx.json(buckets, HTTP.ResultCodes.RS_2.Ok);
231
- },
232
- });
233
- }
234
- const getBucketByNameRoute = StaticAssetRouteOptionsUtility.readOverride({
235
- route: routes?.getBucketByName,
236
- });
237
- if (getBucketByNameRoute.isEnabled) {
238
- this.bindRoute({
239
- configs: { ...definitions.GET_BUCKET_BY_NAME, ...getBucketByNameRoute.override },
240
- }).to({
241
- handler: async (ctx) => {
242
- const params = ctx.req.valid('param');
243
- const bucketName = await resolveBucket({
244
- configured: bucket,
245
- param: params.bucketName,
246
- });
247
- if (!helper.isValidBucketName({ bucket: { name: bucketName } })) {
248
- throw getError({ error: StaticAssetErrors.BUCKET_NAME_INVALID });
249
- }
250
- const found = await helper.getBucket({ bucket: { name: bucketName } });
251
- return ctx.json(found, HTTP.ResultCodes.RS_2.Ok);
252
- },
253
- });
254
- }
255
- const createBucketRoute = StaticAssetRouteOptionsUtility.readOverride({
256
- route: routes?.createBucket,
257
- });
258
- if (createBucketRoute.isEnabled) {
259
- this.bindRoute({
260
- configs: { ...definitions.CREATE_BUCKET, ...createBucketRoute.override },
261
- }).to({
262
- handler: async (ctx) => {
263
- const params = ctx.req.valid('param');
264
- const bucketName = await resolveBucket({
265
- configured: bucket,
266
- param: params.bucketName,
267
- });
268
- if (!helper.isValidBucketName({ bucket: { name: bucketName } })) {
269
- throw getError({ error: StaticAssetErrors.BUCKET_NAME_INVALID });
270
- }
271
- const createdBucket = await helper.createBucket({ bucket: { name: bucketName } });
272
- return ctx.json(createdBucket, HTTP.ResultCodes.RS_2.Ok);
273
- },
274
- });
275
- }
276
- const deleteBucketRoute = StaticAssetRouteOptionsUtility.readOverride({
277
- route: routes?.deleteBucket,
278
- });
279
- if (deleteBucketRoute.isEnabled) {
280
- this.bindRoute({
281
- configs: { ...definitions.DELETE_BUCKET, ...deleteBucketRoute.override },
282
- }).to({
283
- handler: async (ctx) => {
284
- const params = ctx.req.valid('param');
285
- const bucketName = await resolveBucket({
286
- configured: bucket,
287
- param: params.bucketName,
288
- });
289
- if (!helper.isValidBucketName({ bucket: { name: bucketName } })) {
290
- throw getError({ error: StaticAssetErrors.BUCKET_NAME_INVALID });
291
- }
292
- const isRemovedBucket = await helper.removeBucket({
293
- bucket: { name: bucketName },
294
- });
295
- return ctx.json({ isDeleted: isRemovedBucket }, HTTP.ResultCodes.RS_2.Ok);
296
- },
297
- });
298
- }
299
- }
300
- const getObjectByNameRoute = StaticAssetRouteOptionsUtility.readOverride({
301
- route: routes?.getObjectByName,
302
- });
303
- if (getObjectByNameRoute.isEnabled) {
304
- this.bindRoute({
305
- configs: { ...definitions.GET_OBJECT_BY_NAME, ...getObjectByNameRoute.override },
306
- }).to({
307
- handler: async (ctx) => {
308
- const params = ctx.req.valid('param');
309
- const bucketName = await resolveBucket({
310
- configured: bucket,
311
- param: params.bucketName,
312
- });
313
- const objectName = readObjectName(params.objectName);
314
- if (!helper.isValidBucketName({ bucket: { name: bucketName } })) {
315
- throw getError({ error: StaticAssetErrors.BUCKET_NAME_INVALID });
316
- }
317
- if (!helper.isValidObjectKey({
318
- object: { key: objectName },
319
- maxDepth: objectKeyMaxDepth,
320
- })) {
321
- throw getError({ error: StaticAssetErrors.OBJECT_NAME_INVALID });
322
- }
323
- // Before any storage call: a key outside the scope must not even be probed.
324
- StaticAssetKeyScopeUtility.assertInScope({ key: objectName, keyPrefix });
325
- const fileStat = await helper.getStat({
326
- bucket: { name: bucketName },
327
- object: { key: objectName },
328
- });
329
- const { size, metadata } = fileStat;
330
- applyMetadataHeaders({ ctx, metadata });
331
- const served = StaticAssetControllerFactory.resolveServedContentType({
332
- helper,
333
- object: { key: objectName },
334
- });
335
- ctx.header(HTTP.Headers.CONTENT_TYPE, served.contentType);
336
- ctx.header('x-content-type-options', 'nosniff');
337
- // Sandboxed even when renderable, so an unforeseen renderable type cannot reach this origin.
338
- ctx.header(HTTP.Headers.CONTENT_SECURITY_POLICY, 'sandbox');
339
- // Advertised unconditionally: a player only offers seeking once it sees this.
340
- ctx.header('accept-ranges', 'bytes');
341
- // A type outside the allow-list downloads instead of rendering; that is the XSS boundary.
342
- if (!served.isRenderable) {
343
- const inlineName = objectName.split('/').pop() ?? objectName;
344
- ctx.header(HTTP.Headers.CONTENT_DISPOSITION, RequestUtility.buildContentDispositionHeader({
345
- filename: inlineName,
346
- type: 'attachment',
347
- }));
348
- }
349
- const range = readByteRange({ header: ctx.req.header('range'), size });
350
- if (range) {
351
- ctx.header(HTTP.Headers.CONTENT_LENGTH, String(range.end - range.start + 1));
352
- ctx.header(HTTP.Headers.CONTENT_RANGE, `bytes ${range.start}-${range.end}/${size}`);
353
- }
354
- else {
355
- ctx.header(HTTP.Headers.CONTENT_LENGTH, size.toString());
356
- }
357
- // The web stream is what a Response body wants, so no Node Readable sits in between.
358
- const stream = await helper.getObjectStream({
359
- bucket: { name: bucketName },
360
- object: { key: objectName },
361
- ...(range ? { range } : {}),
362
- });
363
- return new Response(stream, {
364
- headers: ctx.res.headers,
365
- status: range ? HTTP.ResultCodes.RS_2.PartialContent : HTTP.ResultCodes.RS_2.Ok,
366
- });
367
- },
368
- });
369
- }
370
- const downloadObjectByNameRoute = StaticAssetRouteOptionsUtility.readOverride({
371
- route: routes?.downloadObjectByName,
372
- });
373
- if (downloadObjectByNameRoute.isEnabled) {
374
- this.bindRoute({
375
- configs: {
376
- ...definitions.DOWNLOAD_OBJECT_BY_NAME,
377
- ...downloadObjectByNameRoute.override,
378
- },
379
- }).to({
380
- handler: async (ctx) => {
381
- const params = ctx.req.valid('param');
382
- const bucketName = await resolveBucket({
383
- configured: bucket,
384
- param: params.bucketName,
385
- });
386
- const objectName = readObjectName(params.objectName);
387
- if (!helper.isValidBucketName({ bucket: { name: bucketName } })) {
388
- throw getError({ error: StaticAssetErrors.BUCKET_NAME_INVALID });
389
- }
390
- if (!helper.isValidObjectKey({
391
- object: { key: objectName },
392
- maxDepth: objectKeyMaxDepth,
393
- })) {
394
- throw getError({ error: StaticAssetErrors.OBJECT_NAME_INVALID });
395
- }
396
- // Before any storage call: a key outside the scope must not even be probed.
397
- StaticAssetKeyScopeUtility.assertInScope({ key: objectName, keyPrefix });
398
- const fileStat = await helper.getStat({
399
- bucket: { name: bucketName },
400
- object: { key: objectName },
401
- });
402
- const { size, metadata } = fileStat;
403
- applyMetadataHeaders({ ctx, metadata });
404
- // Download always attaches, so the served type only has to be honest, never renderable.
405
- const served = StaticAssetControllerFactory.resolveServedContentType({
406
- helper,
407
- object: { key: objectName },
408
- });
409
- ctx.header(HTTP.Headers.CONTENT_TYPE, served.contentType);
410
- ctx.header(HTTP.Headers.CONTENT_LENGTH, size.toString());
411
- const fileName = objectName.split('/').pop() ?? objectName;
412
- ctx.header(HTTP.Headers.CONTENT_DISPOSITION, RequestUtility.buildContentDispositionHeader({
413
- filename: fileName,
414
- type: 'attachment',
415
- }));
416
- ctx.header('x-content-type-options', 'nosniff');
417
- ctx.header(HTTP.Headers.CONTENT_SECURITY_POLICY, 'sandbox');
418
- const stream = await helper.getObjectStream({
419
- bucket: { name: bucketName },
420
- object: { key: objectName },
421
- });
422
- return new Response(stream, {
423
- headers: ctx.res.headers,
424
- status: HTTP.ResultCodes.RS_2.Ok,
425
- });
426
- },
427
- });
428
- }
429
- const uploadRoute = StaticAssetRouteOptionsUtility.readOverride({ route: routes?.upload });
430
- if (uploadRoute.isEnabled) {
431
- const uploadMiddleware = maxBytes === undefined
432
- ? uploadRoute.override.middleware
433
- : StaticAssetRouteOptionsUtility.appendLengthGuard({
434
- middleware: uploadRoute.override.middleware,
435
- maxBytes,
436
- maxFiles: options?.parseMultipartBody?.maxFiles ?? StaticAssetDefaults.MAX_UPLOAD_FILES,
437
- });
438
- this.bindRoute({
439
- configs: {
440
- ...definitions.UPLOAD,
441
- ...uploadRoute.override,
442
- middleware: uploadMiddleware,
443
- },
444
- }).to({
445
- handler: async (ctx) => {
446
- // A configured bucket drops `params` from this route entirely, so it is read only when it exists.
447
- const bucketParam = hasConfiguredBucket
448
- ? undefined
449
- : ctx.req.valid('param').bucketName;
450
- const bucketName = await resolveBucket({ configured: bucket, param: bucketParam });
451
- if (!helper.isValidBucketName({ bucket: { name: bucketName } })) {
452
- throw getError({ error: StaticAssetErrors.BUCKET_NAME_INVALID });
453
- }
454
- const validateFolderPath = (folderPath) => {
455
- const normalizedFolder = folderPath.replace(/^\/+|\/+$/g, '');
456
- if (!normalizedFolder) {
457
- throw getError({ error: StaticAssetErrors.FOLDER_PATH_INVALID });
458
- }
459
- // maxFolderDepth excludes the filename, so it is compared directly against segment count.
460
- const folderSegments = normalizedFolder.split('/');
461
- if (folderSegments.length > maxFolderDepth) {
462
- throw getError({
463
- error: StaticAssetErrors.FOLDER_DEPTH_EXCEEDED,
464
- message: `Folder path exceeds max depth of ${maxFolderDepth}`,
465
- });
466
- }
467
- const invalidSegmentIndex = folderSegments.findIndex((segment) => !helper.isValidSegment({ segment }));
468
- if (invalidSegmentIndex !== -1) {
469
- throw getError({
470
- error: StaticAssetErrors.FOLDER_SEGMENT_INVALID,
471
- message: `Invalid folder path segment: ${folderSegments[invalidSegmentIndex]}`,
472
- });
473
- }
474
- };
475
- refuseLabelsInQuery({ query: ctx.req.query() });
476
- const { files: filesArray, fields } = await RequestUtility.parseMultipartBody({
477
- context: ctx,
478
- storage: options?.parseMultipartBody?.storage,
479
- uploadDir: options?.parseMultipartBody?.uploadDir,
480
- maxFiles: options?.parseMultipartBody?.maxFiles ?? StaticAssetDefaults.MAX_UPLOAD_FILES,
481
- });
482
- const spoolPaths = filesArray
483
- .map((file) => file.path)
484
- .filter((filePath) => Boolean(filePath));
485
- let query;
486
- let uploaded;
487
- // From here every exit removes the spool files, the validation failures included.
488
- try {
489
- // Labels travel with the payload, not the URL, so the folder check waits for the parse.
490
- query = readUploadLabels({ fields });
491
- const folderPath = query.folderPath;
492
- if (folderPath) {
493
- validateFolderPath(folderPath);
494
- }
495
- // `storage: 'disk'` spools the payload to `uploadDir` and returns `path` instead of `buffer`; the storage helpers only ever write `buffer`, so it must be read back.
496
- const modifiedFiles = filesArray.map((file) => {
497
- const buffer = file.buffer ?? (file.path ? readFileSync(file.path) : undefined);
498
- if (!buffer?.length) {
499
- throw getError({
500
- error: StaticAssetErrors.FILE_EMPTY,
501
- message: `Empty file content | name: ${file.originalname}`,
502
- });
503
- }
504
- // Authoritative: `buffer.length`, not the client-declared `size`.
505
- if (maxBytes !== undefined && buffer.length > maxBytes) {
506
- throw getError({
507
- error: StaticAssetErrors.UPLOAD_TOO_LARGE,
508
- message: `File ${file.originalname} of ${buffer.length} bytes exceeds the maximum of ${maxBytes}`,
509
- });
510
- }
511
- return {
512
- originalName: file.originalname,
513
- mimetype: file.mimetype,
514
- buffer,
515
- size: file.size,
516
- encoding: file.encoding,
517
- folderPath: folderPath ?? undefined,
518
- };
519
- });
520
- // Built per request: the hook is offered the bucket, which only the route knows. With
521
- // neither hook nor scope, `normalizeNameFn` stays exactly as configured. Under a scope,
522
- // the component's own default is placed inside it; an application hook's key is
523
- // checked, never rewritten, because the application may record that key elsewhere.
524
- const normalizeNameFn = resolveObjectName || keyPrefix !== undefined
525
- ? (naming) => {
526
- if (isScopedDefaultNaming &&
527
- !helper.isValidSegment({ segment: naming.file.originalName })) {
528
- throw getError({ message: '[upload] Invalid original file name' });
529
- }
530
- const defaultKey = options?.normalizeNameFn
531
- ? options.normalizeNameFn(naming)
532
- : `${keyPrefix ?? ''}${defaultObjectName(naming)}`;
533
- const key = resolveObjectName
534
- ? resolveObjectName({
535
- bucket: { name: bucketName },
536
- file: naming.file,
537
- defaultKey,
538
- })
539
- : defaultKey;
540
- if (!StaticAssetKeyScopeUtility.isInScope({ key, keyPrefix })) {
541
- throw getError({
542
- error: StaticAssetErrors.OBJECT_KEY_OUT_OF_SCOPE,
543
- message: `Object key is outside the key prefix of this controller | key: ${key} | keyPrefix: ${keyPrefix}`,
544
- });
545
- }
546
- return key;
547
- }
548
- : options?.normalizeNameFn;
549
- const result = await helper.upload({
550
- bucket: { name: bucketName },
551
- files: modifiedFiles,
552
- normalizeNameFn,
553
- normalizeLinkFn,
554
- // Without this the helper re-validates against its own hard default of 2, so an app configured for a deeper tree spools the body and only then fails inside the helper.
555
- maxFolderDepth: objectKeyMaxDepth,
556
- });
557
- uploaded = result;
558
- }
559
- finally {
560
- this.removeSpoolFiles({ paths: spoolPaths });
561
- }
562
- if (!useMetaLink || !metaLink) {
563
- return ctx.json(uploaded, HTTP.ResultCodes.RS_2.Ok);
564
- }
565
- const results = [];
566
- for (const uploadResult of uploaded) {
567
- try {
568
- const fileStat = await helper.getStat({
569
- bucket: uploadResult.bucket,
570
- object: uploadResult.object,
571
- });
572
- const createdMetaLink = await StaticAssetMetaLinkUtility.createRow({
573
- metaLink,
574
- helper,
575
- storage,
576
- uploadResult,
577
- fileStat,
578
- query,
579
- });
580
- results.push({ ...uploadResult, metaLink: { data: createdMetaLink } });
581
- }
582
- catch (error) {
583
- this.logger
584
- .for('UPLOAD')
585
- .error('Failed to create MetaLink | objectName: %s | Error: %s', uploadResult.object.key, error);
586
- results.push({
587
- ...uploadResult,
588
- // A CODE, never the driver text. This handler returns 200, so it bypasses the
589
- // error middleware and `database.handler` - the two places that strip
590
- // `detail`/`table`/`constraint` - and shipped raw constraint names to the client.
591
- // The real error is already logged in full immediately above.
592
- metaLink: { error: StaticAssetMetaLinkCodes.CREATE_FAILED },
593
- });
594
- }
595
- }
596
- return ctx.json(results, HTTP.ResultCodes.RS_2.Ok);
597
- },
598
- });
599
- }
600
- const deleteObjectRoute = StaticAssetRouteOptionsUtility.readOverride({
601
- route: routes?.deleteObject,
602
- });
603
- if (deleteObjectRoute.isEnabled) {
604
- this.bindRoute({
605
- configs: { ...definitions.DELETE_OBJECT, ...deleteObjectRoute.override },
606
- }).to({
607
- handler: async (ctx) => {
608
- const params = ctx.req.valid('param');
609
- const bucketName = await resolveBucket({
610
- configured: bucket,
611
- param: params.bucketName,
612
- });
613
- const objectName = readObjectName(params.objectName);
614
- if (!helper.isValidBucketName({ bucket: { name: bucketName } })) {
615
- throw getError({ error: StaticAssetErrors.BUCKET_NAME_INVALID });
616
- }
617
- if (!helper.isValidObjectKey({
618
- object: { key: objectName },
619
- maxDepth: objectKeyMaxDepth,
620
- })) {
621
- throw getError({ error: StaticAssetErrors.OBJECT_NAME_INVALID });
622
- }
623
- // Before any storage call: a key outside the scope must not even be probed.
624
- StaticAssetKeyScopeUtility.assertInScope({ key: objectName, keyPrefix });
625
- // Deliberately idempotent: S3 answers 200 for a key that was never there, and consumers
626
- // already depend on it. `disk` throws instead, so the two are reconciled here, not below.
627
- try {
628
- await helper.removeObject({
629
- bucket: { name: bucketName },
630
- object: { key: objectName },
631
- });
632
- }
633
- catch (error) {
634
- if (!StorageUtility.isNotFoundError({ error })) {
635
- throw error;
636
- }
637
- }
638
- if (!useMetaLink || !metaLink) {
639
- return ctx.json({ success: true }, HTTP.ResultCodes.RS_2.Ok);
640
- }
641
- const deleteRepository = await ResolverUtility.resolveValueAsync({
642
- value: metaLink.repository,
643
- });
644
- deleteRepository
645
- .deleteBy({
646
- where: {
647
- bucketName,
648
- objectName,
649
- },
650
- })
651
- .then(() => {
652
- this.logger
653
- .for('DELETE_OBJECT')
654
- .info('Successfully to delete MetaLink for %s/%s', bucketName, objectName);
655
- })
656
- .catch((error) => {
657
- this.logger
658
- .for('DELETE_OBJECT')
659
- .error('Failed to delete MetaLink | bucket: %s | objectName: %s | Error: %s', bucketName, objectName, error);
660
- });
661
- return ctx.json({ success: true }, HTTP.ResultCodes.RS_2.Ok);
662
- },
663
- });
664
- }
665
- const listObjectsRoute = StaticAssetRouteOptionsUtility.readOverride({
666
- route: routes?.listObjects,
55
+ extend?.before?.({ controller: this, helper, basePath });
56
+ StaticAssetRouteTable.register({
57
+ controller: this,
58
+ env: { ...env, logger: this.logger },
667
59
  });
668
- if (listObjectsRoute.isEnabled) {
669
- this.bindRoute({
670
- configs: { ...definitions.LIST_OBJECTS, ...listObjectsRoute.override },
671
- }).to({
672
- handler: async (ctx) => {
673
- // A configured bucket drops `params` from this route entirely, so it is read only when it exists.
674
- const bucketParam = hasConfiguredBucket
675
- ? undefined
676
- : ctx.req.valid('param').bucketName;
677
- const bucketName = await resolveBucket({ configured: bucket, param: bucketParam });
678
- const { prefix, recursive, maxKeys } = ctx.req.valid('query');
679
- if (!helper.isValidBucketName({ bucket: { name: bucketName } })) {
680
- throw getError({ error: StaticAssetErrors.BUCKET_NAME_INVALID });
681
- }
682
- // A NaN or 0 maxKeys is silently treated as "unlimited" by the storage backends, so an unparsable value must be rejected instead of forwarded.
683
- let resolvedMaxKeys;
684
- if (maxKeys !== undefined) {
685
- resolvedMaxKeys = Number(maxKeys);
686
- if (!Number.isInteger(resolvedMaxKeys) || resolvedMaxKeys < 1) {
687
- throw getError({
688
- error: StaticAssetErrors.MAX_KEYS_INVALID,
689
- message: `Invalid maxKeys | Expected a positive integer | value: ${maxKeys}`,
690
- });
691
- }
692
- }
693
- const scoped = StaticAssetKeyScopeUtility.resolveListPrefix({ prefix, keyPrefix });
694
- if (scoped.isOutOfScope) {
695
- return ctx.json([], HTTP.ResultCodes.RS_2.Ok);
696
- }
697
- const objects = await helper.listObjects({
698
- bucket: { name: bucketName },
699
- prefix: scoped.prefix,
700
- useRecursive: recursive === 'true',
701
- maxKeys: resolvedMaxKeys,
702
- });
703
- return ctx.json(objects, HTTP.ResultCodes.RS_2.Ok);
704
- },
705
- });
706
- }
707
- if (directUpload) {
708
- if (!hasConfiguredBucket) {
709
- throw getError({
710
- message: `[${name}] directUpload needs controller.bucket | a policy names one bucket, and a bucket in the URL is a bucket the caller chooses`,
711
- });
712
- }
713
- const { policyService, commitService } = opts;
714
- if (!policyService || !commitService) {
715
- throw getError({
716
- message: `[${name}] directUpload needs policyService and commitService | the component builds and binds them; a caller of StaticAssetControllerFactory.build passes its own`,
717
- });
718
- }
719
- const uploadPolicyRoute = StaticAssetRouteOptionsUtility.readOverride({
720
- route: routes?.uploadPolicy,
721
- });
722
- if (uploadPolicyRoute.isEnabled) {
723
- this.bindRoute({
724
- configs: { ...definitions.UPLOAD_POLICY, ...uploadPolicyRoute.override },
725
- }).to({
726
- handler: async (ctx) => {
727
- const result = await directUpload.authorize({ context: ctx });
728
- if (!result) {
729
- throw getError({ error: StaticAssetErrors.UPLOAD_NOT_AUTHORIZED });
730
- }
731
- const { files } = ctx.req.valid('json');
732
- const policies = await policyService.issuePolicies({ files });
733
- return ctx.json(policies, HTTP.ResultCodes.RS_2.Ok);
734
- },
735
- });
736
- }
737
- const uploadCommitRoute = StaticAssetRouteOptionsUtility.readOverride({
738
- route: routes?.uploadCommit,
739
- });
740
- if (uploadCommitRoute.isEnabled) {
741
- this.bindRoute({
742
- configs: { ...definitions.UPLOAD_COMMIT, ...uploadCommitRoute.override },
743
- }).to({
744
- handler: async (ctx) => {
745
- const commitQuery = ctx.req.query();
746
- refuseLabelsInQuery({ query: commitQuery, names: COMMIT_LABEL_NAMES });
747
- refuseLabelsInQuery({
748
- query: commitQuery,
749
- names: ['folderPath'],
750
- reason: 'folderPath was decided when the upload policy was issued; the commit route cannot move the object',
751
- });
752
- const { commitToken, ...labels } = ctx.req.valid('json');
753
- const result = await commitService.commit({
754
- commitToken,
755
- labels: readUploadLabels({ fields: labels }),
756
- });
757
- return ctx.json(result, HTTP.ResultCodes.RS_2.Ok);
758
- },
759
- });
760
- }
761
- }
762
- if (useMetaLink && metaLink) {
763
- const recreateMetaLinkRoute = StaticAssetRouteOptionsUtility.readOverride({
764
- route: routes?.recreateMetaLink,
765
- });
766
- if (recreateMetaLinkRoute.isEnabled) {
767
- this.bindRoute({
768
- configs: { ...definitions.RECREATE_METALINK, ...recreateMetaLinkRoute.override },
769
- }).to({
770
- handler: async (ctx) => {
771
- // This route takes no labels anywhere: one in the query would land an unlabelled row.
772
- refuseLabelsInQuery({
773
- query: ctx.req.query(),
774
- reason: 'This route recreates a MetaLink for an existing object and takes no labels',
775
- });
776
- const params = ctx.req.valid('param');
777
- const bucketName = await resolveBucket({
778
- configured: bucket,
779
- param: params.bucketName,
780
- });
781
- const objectName = readObjectName(params.objectName);
782
- if (!helper.isValidBucketName({ bucket: { name: bucketName } })) {
783
- throw getError({ error: StaticAssetErrors.BUCKET_NAME_INVALID });
784
- }
785
- if (!helper.isValidObjectKey({
786
- object: { key: objectName },
787
- maxDepth: objectKeyMaxDepth,
788
- })) {
789
- throw getError({ error: StaticAssetErrors.OBJECT_NAME_INVALID });
790
- }
791
- // Before any storage call: a key outside the scope must not even be probed.
792
- StaticAssetKeyScopeUtility.assertInScope({ key: objectName, keyPrefix });
793
- const bucketRef = { name: bucketName };
794
- const object = { key: objectName };
795
- const fileStat = await helper.getStat({ bucket: bucketRef, object });
796
- const link = options?.normalizeLinkFn
797
- ? options.normalizeLinkFn({ bucket: bucketRef, object })
798
- : StaticAssetControllerFactory.buildObjectLink({
799
- basePath: normalizedBasePath,
800
- bucket: bucketRef,
801
- object,
802
- hasConfiguredBucket,
803
- rawObjectPath,
804
- });
805
- const refreshed = await StaticAssetMetaLinkUtility.refreshRows({
806
- metaLink,
807
- helper,
808
- bucket: bucketRef,
809
- object,
810
- link,
811
- fileStat,
812
- });
813
- if (refreshed.count > 0) {
814
- return ctx.json({
815
- success: true,
816
- action: MetaLinkRecreateActions.REFRESHED,
817
- count: refreshed.count,
818
- metaLink: refreshed.data[0],
819
- metaLinks: refreshed.data,
820
- }, HTTP.ResultCodes.RS_2.Ok);
821
- }
822
- // Not atomic with the refresh above: two concurrent calls may both create, which the
823
- // table allows - rows per pair are deliberately not unique.
824
- const created = await StaticAssetMetaLinkUtility.createRow({
825
- metaLink,
826
- helper,
827
- storage,
828
- uploadResult: StaticAssetMetaLinkUtility.buildStoredUploadResult({
829
- helper,
830
- bucket: bucketRef,
831
- object,
832
- link,
833
- fileStat,
834
- }),
835
- fileStat,
836
- query: {},
837
- });
838
- return ctx.json({
839
- success: true,
840
- action: MetaLinkRecreateActions.CREATED,
841
- count: 1,
842
- metaLink: created,
843
- metaLinks: [created],
844
- }, HTTP.ResultCodes.RS_2.Ok);
845
- },
846
- });
847
- }
848
- }
849
60
  // Last, so a built-in route always wins a path collision with an application's own.
850
- defineExtraRoutes?.({ controller: this, helper, basePath: normalizedBasePath });
61
+ extend?.after?.({ controller: this, helper, basePath });
851
62
  }
852
63
  };
853
64
  GeneratedStaticAssetController = __decorate([