@webiny/api-file-manager 6.5.2-beta.0 → 6.5.2-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/domain/file/errors.d.ts +12 -0
  2. package/domain/file/errors.js +10 -2
  3. package/domain/file/errors.js.map +1 -1
  4. package/domain/settings/errors.d.ts +4 -0
  5. package/domain/settings/errors.js +8 -1
  6. package/domain/settings/errors.js.map +1 -1
  7. package/domain/settings/validation.d.ts +9 -1
  8. package/domain/settings/validation.js +33 -11
  9. package/domain/settings/validation.js.map +1 -1
  10. package/features/assetDelivery/privateFiles/PrivateAuthenticatedAuthorizer.d.ts +9 -1
  11. package/features/assetDelivery/privateFiles/PrivateAuthenticatedAuthorizer.js +14 -9
  12. package/features/assetDelivery/privateFiles/PrivateAuthenticatedAuthorizer.js.map +1 -1
  13. package/features/file/CreateFile/CreateFileRepository.js +8 -2
  14. package/features/file/CreateFile/CreateFileRepository.js.map +1 -1
  15. package/features/file/CreateFile/CreateFileUseCase.js +15 -8
  16. package/features/file/CreateFile/CreateFileUseCase.js.map +1 -1
  17. package/features/file/CreateFile/abstractions.d.ts +3 -1
  18. package/features/file/CreateFile/abstractions.js.map +1 -1
  19. package/features/file/CreateFilesInBatch/CreateFilesInBatchUseCase.d.ts +3 -1
  20. package/features/file/CreateFilesInBatch/CreateFilesInBatchUseCase.js +13 -2
  21. package/features/file/CreateFilesInBatch/CreateFilesInBatchUseCase.js.map +1 -1
  22. package/features/file/CreateFilesInBatch/abstractions.d.ts +2 -1
  23. package/features/file/CreateFilesInBatch/abstractions.js.map +1 -1
  24. package/features/file/ListTags/ListTagsUseCase.d.ts +3 -1
  25. package/features/file/ListTags/ListTagsUseCase.js +10 -2
  26. package/features/file/ListTags/ListTagsUseCase.js.map +1 -1
  27. package/features/file/UpdateFile/UpdateFileUseCase.js +7 -6
  28. package/features/file/UpdateFile/UpdateFileUseCase.js.map +1 -1
  29. package/features/file/shared/isValidFileKey.d.ts +8 -0
  30. package/features/file/shared/isValidFileKey.js +10 -0
  31. package/features/file/shared/isValidFileKey.js.map +1 -0
  32. package/features/settings/SettingsInstaller/SettingsInstaller.d.ts +3 -1
  33. package/features/settings/SettingsInstaller/SettingsInstaller.js +8 -5
  34. package/features/settings/SettingsInstaller/SettingsInstaller.js.map +1 -1
  35. package/features/settings/UpdateSettings/UpdateSettingsUseCase.d.ts +3 -1
  36. package/features/settings/UpdateSettings/UpdateSettingsUseCase.js +14 -4
  37. package/features/settings/UpdateSettings/UpdateSettingsUseCase.js.map +1 -1
  38. package/features/settings/UpdateSettings/abstractions.d.ts +2 -0
  39. package/features/settings/UpdateSettings/abstractions.js.map +1 -1
  40. package/features/upload/CreateMultiPartUpload/abstractions.d.ts +4 -0
  41. package/features/upload/CreateMultiPartUpload/abstractions.js.map +1 -1
  42. package/features/upload/GetUploadPayload/abstractions.d.ts +8 -1
  43. package/features/upload/GetUploadPayload/abstractions.js.map +1 -1
  44. package/features/upload/WriteFileMetadata/MetadataWriter.js +5 -1
  45. package/features/upload/WriteFileMetadata/MetadataWriter.js.map +1 -1
  46. package/features/upload/utils/FileNormalizer.js +27 -0
  47. package/features/upload/utils/FileNormalizer.js.map +1 -1
  48. package/graphql/FmGraphQLSchema.js +9 -2
  49. package/graphql/FmGraphQLSchema.js.map +1 -1
  50. package/graphql/FmUploadGraphQLSchema.js +8 -3
  51. package/graphql/FmUploadGraphQLSchema.js.map +1 -1
  52. package/package.json +18 -18
@@ -31,10 +31,12 @@ export declare class FileDeleteError extends BaseError {
31
31
  }
32
32
  export declare class FileAlreadyExistsError extends BaseError<{
33
33
  key: string;
34
+ id?: string;
34
35
  }> {
35
36
  readonly code: "FileManager/File/AlreadyExistsError";
36
37
  constructor(data: {
37
38
  key: string;
39
+ id?: string;
38
40
  });
39
41
  }
40
42
  export declare class InvalidFileSizeError extends BaseError<{
@@ -57,3 +59,13 @@ export declare class InvalidFileTypeError extends BaseError<{
57
59
  type: string;
58
60
  });
59
61
  }
62
+ export declare class InvalidFileKeyError extends BaseError<{
63
+ id: string;
64
+ key: string;
65
+ }> {
66
+ readonly code: "FileManager/File/InvalidFileKeyError";
67
+ constructor(data: {
68
+ id: string;
69
+ key: string;
70
+ });
71
+ }
@@ -54,7 +54,7 @@ class FileDeleteError extends BaseError {
54
54
  class FileAlreadyExistsError extends BaseError {
55
55
  constructor(data){
56
56
  super({
57
- message: `File with key "${data.key}" already exists.`,
57
+ message: data.id ? `File with id "${data.id}" already exists.` : `File with key "${data.key}" already exists.`,
58
58
  data
59
59
  }), this.code = "FileManager/File/AlreadyExistsError";
60
60
  }
@@ -75,6 +75,14 @@ class InvalidFileTypeError extends BaseError {
75
75
  }), this.code = "FileManager/File/InvalidFileTypeError";
76
76
  }
77
77
  }
78
- export { FileAlreadyExistsError, FileCreateError, FileDeleteError, FileListError, FileNotAuthorizedError, FileNotFoundError, FilePersistenceError, FileUpdateError, InvalidFileSizeError, InvalidFileTypeError };
78
+ class InvalidFileKeyError extends BaseError {
79
+ constructor(data){
80
+ super({
81
+ message: `File key "${data.key}" is not valid for file "${data.id}".`,
82
+ data
83
+ }), this.code = "FileManager/File/InvalidFileKeyError";
84
+ }
85
+ }
86
+ export { FileAlreadyExistsError, FileCreateError, FileDeleteError, FileListError, FileNotAuthorizedError, FileNotFoundError, FilePersistenceError, FileUpdateError, InvalidFileKeyError, InvalidFileSizeError, InvalidFileTypeError };
79
87
 
80
88
  //# sourceMappingURL=errors.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"domain/file/errors.js","sources":["../../../src/domain/file/errors.ts"],"sourcesContent":["import { BaseError } from \"@webiny/feature/api\";\n\nexport class FilePersistenceError extends BaseError {\n override readonly code = \"FileManager/File/PersistenceError\" as const;\n\n constructor(error: Error) {\n super({\n message: error.message\n });\n }\n}\n\nexport class FileNotFoundError extends BaseError<{ id: string }> {\n override readonly code = \"FileManager/File/NotFoundError\" as const;\n\n constructor(id: string) {\n super({\n message: `File with ID \"${id}\" not found.`,\n data: { id }\n });\n }\n}\n\nexport class FileNotAuthorizedError extends BaseError {\n override readonly code = \"FileManager/File/NotAuthorizedError\" as const;\n\n constructor() {\n super({\n message: `Not authorized.`\n });\n }\n}\n\nexport class FileListError extends BaseError {\n override readonly code = \"FileManager/File/ListError\" as const;\n\n constructor(error: Error) {\n super({\n message: `Error listing files: ${error.message}`\n });\n }\n}\n\nexport class FileCreateError extends BaseError {\n override readonly code = \"FileManager/File/CreateError\" as const;\n\n constructor(error: Error) {\n super({\n message: `Error creating file: ${error.message}`\n });\n }\n}\n\nexport class FileUpdateError extends BaseError {\n override readonly code = \"FileManager/File/UpdateError\" as const;\n\n constructor(error: Error) {\n super({\n message: `Error updating file: ${error.message}`\n });\n }\n}\n\nexport class FileDeleteError extends BaseError {\n override readonly code = \"FileManager/File/DeleteError\" as const;\n\n constructor(error: Error) {\n super({\n message: `Error deleting file: ${error.message}`\n });\n }\n}\n\nexport class FileAlreadyExistsError extends BaseError<{ key: string }> {\n override readonly code = \"FileManager/File/AlreadyExistsError\" as const;\n\n constructor(data: { key: string }) {\n super({\n message: `File with key \"${data.key}\" already exists.`,\n data\n });\n }\n}\n\nexport class InvalidFileSizeError extends BaseError<{\n size: number;\n minSize: number;\n maxSize: number;\n}> {\n override readonly code = \"FileManager/File/InvalidFileSizeError\" as const;\n\n constructor(data: { size: number; minSize: number; maxSize: number }) {\n super({\n message: `File size ${data.size} bytes is outside allowed range (${data.minSize}-${data.maxSize} bytes).`,\n data\n });\n }\n}\n\nexport class InvalidFileTypeError extends BaseError<{ type: string }> {\n override readonly code = \"FileManager/File/InvalidFileTypeError\" as const;\n\n constructor(data: { type: string }) {\n super({\n message: `File type \"${data.type}\" is not allowed.`,\n data\n });\n }\n}\n"],"names":["FilePersistenceError","BaseError","error","FileNotFoundError","id","FileNotAuthorizedError","FileListError","FileCreateError","FileUpdateError","FileDeleteError","FileAlreadyExistsError","data","InvalidFileSizeError","InvalidFileTypeError"],"mappings":";AAEO,MA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D,CAAE;QAClE,KAAK,CAAC;YACF,SAAS,CAAC,UAAU,EAAEA,KAAK,IAAI,CAAC,iCAAiC,EAAEA,KAAK,OAAO,CAAC,CAAC,EAAEA,KAAK,OAAO,CAAC,QAAQ,CAAC;YACzGA;QACJ,SANc,IAAI,GAAG;IAOzB;AACJ;AAEO,MAAME,6BAA6BZ;IAGtC,YAAYU,IAAsB,CAAE;QAChC,KAAK,CAAC;YACF,SAAS,CAAC,WAAW,EAAEA,KAAK,IAAI,CAAC,iBAAiB,CAAC;YACnDA;QACJ,SANc,IAAI,GAAG;IAOzB;AACJ"}
1
+ {"version":3,"file":"domain/file/errors.js","sources":["../../../src/domain/file/errors.ts"],"sourcesContent":["import { BaseError } from \"@webiny/feature/api\";\n\nexport class FilePersistenceError extends BaseError {\n override readonly code = \"FileManager/File/PersistenceError\" as const;\n\n constructor(error: Error) {\n super({\n message: error.message\n });\n }\n}\n\nexport class FileNotFoundError extends BaseError<{ id: string }> {\n override readonly code = \"FileManager/File/NotFoundError\" as const;\n\n constructor(id: string) {\n super({\n message: `File with ID \"${id}\" not found.`,\n data: { id }\n });\n }\n}\n\nexport class FileNotAuthorizedError extends BaseError {\n override readonly code = \"FileManager/File/NotAuthorizedError\" as const;\n\n constructor() {\n super({\n message: `Not authorized.`\n });\n }\n}\n\nexport class FileListError extends BaseError {\n override readonly code = \"FileManager/File/ListError\" as const;\n\n constructor(error: Error) {\n super({\n message: `Error listing files: ${error.message}`\n });\n }\n}\n\nexport class FileCreateError extends BaseError {\n override readonly code = \"FileManager/File/CreateError\" as const;\n\n constructor(error: Error) {\n super({\n message: `Error creating file: ${error.message}`\n });\n }\n}\n\nexport class FileUpdateError extends BaseError {\n override readonly code = \"FileManager/File/UpdateError\" as const;\n\n constructor(error: Error) {\n super({\n message: `Error updating file: ${error.message}`\n });\n }\n}\n\nexport class FileDeleteError extends BaseError {\n override readonly code = \"FileManager/File/DeleteError\" as const;\n\n constructor(error: Error) {\n super({\n message: `Error deleting file: ${error.message}`\n });\n }\n}\n\nexport class FileAlreadyExistsError extends BaseError<{ key: string; id?: string }> {\n override readonly code = \"FileManager/File/AlreadyExistsError\" as const;\n\n constructor(data: { key: string; id?: string }) {\n super({\n message: data.id\n ? `File with id \"${data.id}\" already exists.`\n : `File with key \"${data.key}\" already exists.`,\n data\n });\n }\n}\n\nexport class InvalidFileSizeError extends BaseError<{\n size: number;\n minSize: number;\n maxSize: number;\n}> {\n override readonly code = \"FileManager/File/InvalidFileSizeError\" as const;\n\n constructor(data: { size: number; minSize: number; maxSize: number }) {\n super({\n message: `File size ${data.size} bytes is outside allowed range (${data.minSize}-${data.maxSize} bytes).`,\n data\n });\n }\n}\n\nexport class InvalidFileTypeError extends BaseError<{ type: string }> {\n override readonly code = \"FileManager/File/InvalidFileTypeError\" as const;\n\n constructor(data: { type: string }) {\n super({\n message: `File type \"${data.type}\" is not allowed.`,\n data\n });\n }\n}\n\nexport class InvalidFileKeyError extends BaseError<{ id: string; key: string }> {\n override readonly code = \"FileManager/File/InvalidFileKeyError\" as const;\n\n constructor(data: { id: string; key: string }) {\n super({\n message: `File key \"${data.key}\" is not valid for file \"${data.id}\".`,\n data\n });\n }\n}\n"],"names":["FilePersistenceError","BaseError","error","FileNotFoundError","id","FileNotAuthorizedError","FileListError","FileCreateError","FileUpdateError","FileDeleteError","FileAlreadyExistsError","data","InvalidFileSizeError","InvalidFileTypeError","InvalidFileKeyError"],"mappings":";AAEO,MAAMA,6BAA6BC;IAGtC,YAAYC,KAAY,CAAE;QACtB,KAAK,CAAC;YACF,SAASA,MAAM,OAAO;QAC1B,SALc,IAAI,GAAG;IAMzB;AACJ;AAEO,MAAMC,0BAA0BF;IAGnC,YAAYG,EAAU,CAAE;QACpB,KAAK,CAAC;YACF,SAAS,CAAC,cAAc,EAAEA,GAAG,YAAY,CAAC;YAC1C,MAAM;gBAAEA;YAAG;QACf,SANc,IAAI,GAAG;IAOzB;AACJ;AAEO,MAAMC,+BAA+BJ;IAGxC,aAAc;QACV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;YACF,SAAS,CAAC,WAAW,EAAEA,KAAK,IAAI,CAAC,iBAAiB,CAAC;YACnDA;QACJ,SANc,IAAI,GAAG;IAOzB;AACJ;AAEO,MAAMG,4BAA4Bb;IAGrC,YAAYU,IAAiC,CAAE;QAC3C,KAAK,CAAC;YACF,SAAS,CAAC,UAAU,EAAEA,KAAK,GAAG,CAAC,yBAAyB,EAAEA,KAAK,EAAE,CAAC,EAAE,CAAC;YACrEA;QACJ,SANc,IAAI,GAAG;IAOzB;AACJ"}
@@ -4,6 +4,10 @@ export declare class SettingsNotFoundError extends BaseError {
4
4
  readonly code: "FileManager/Settings/NotFoundError";
5
5
  constructor();
6
6
  }
7
+ export declare class SettingsNotAuthorizedError extends BaseError {
8
+ readonly code: "FileManager/Settings/NotAuthorizedError";
9
+ constructor();
10
+ }
7
11
  export declare class SettingsUpdateError extends BaseError {
8
12
  readonly code: "FileManager/Settings/UpdateError";
9
13
  constructor(error: Error);
@@ -6,6 +6,13 @@ class SettingsNotFoundError extends BaseError {
6
6
  }), this.code = "FileManager/Settings/NotFoundError";
7
7
  }
8
8
  }
9
+ class SettingsNotAuthorizedError extends BaseError {
10
+ constructor(){
11
+ super({
12
+ message: "Not authorized."
13
+ }), this.code = "FileManager/Settings/NotAuthorizedError";
14
+ }
15
+ }
9
16
  class SettingsUpdateError extends BaseError {
10
17
  constructor(error){
11
18
  super({
@@ -23,6 +30,6 @@ class SettingsValidationError extends BaseError {
23
30
  }), this.code = "FileManager/Settings/ValidationError";
24
31
  }
25
32
  }
26
- export { SettingsNotFoundError, SettingsUpdateError, SettingsValidationError };
33
+ export { SettingsNotAuthorizedError, SettingsNotFoundError, SettingsUpdateError, SettingsValidationError };
27
34
 
28
35
  //# sourceMappingURL=errors.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"domain/settings/errors.js","sources":["../../../src/domain/settings/errors.ts"],"sourcesContent":["import { BaseError } from \"@webiny/feature/api\";\nimport type { OutputErrors } from \"@webiny/utils/createZodError.js\";\n\nexport class SettingsNotFoundError extends BaseError {\n override readonly code = \"FileManager/Settings/NotFoundError\" as const;\n\n constructor() {\n super({\n message: \"File manager settings not found.\"\n });\n }\n}\n\nexport class SettingsUpdateError extends BaseError {\n override readonly code = \"FileManager/Settings/UpdateError\" as const;\n\n constructor(error: Error) {\n super({\n message: `Error updating settings: ${error.message}`\n });\n }\n}\n\ninterface ValidationParams {\n invalidFields: OutputErrors;\n}\n\nexport class SettingsValidationError extends BaseError<ValidationParams> {\n override readonly code = \"FileManager/Settings/ValidationError\" as const;\n\n constructor(invalidFields: OutputErrors) {\n super({\n message: \"Validation failed.\",\n data: { invalidFields }\n });\n }\n}\n"],"names":["SettingsNotFoundError","BaseError","SettingsUpdateError","error","SettingsValidationError","invalidFields"],"mappings":";AAGO,MAAMA,8BAA8BC;IAGvC,aAAc;QACV,KAAK,CAAC;YACF,SAAS;QACb,SALc,IAAI,GAAG;IAMzB;AACJ;AAEO,MAAMC,4BAA4BD;IAGrC,YAAYE,KAAY,CAAE;QACtB,KAAK,CAAC;YACF,SAAS,CAAC,yBAAyB,EAAEA,MAAM,OAAO,EAAE;QACxD,SALc,IAAI,GAAG;IAMzB;AACJ;AAMO,MAAMC,gCAAgCH;IAGzC,YAAYI,aAA2B,CAAE;QACrC,KAAK,CAAC;YACF,SAAS;YACT,MAAM;gBAAEA;YAAc;QAC1B,SANc,IAAI,GAAG;IAOzB;AACJ"}
1
+ {"version":3,"file":"domain/settings/errors.js","sources":["../../../src/domain/settings/errors.ts"],"sourcesContent":["import { BaseError } from \"@webiny/feature/api\";\nimport type { OutputErrors } from \"@webiny/utils/createZodError.js\";\n\nexport class SettingsNotFoundError extends BaseError {\n override readonly code = \"FileManager/Settings/NotFoundError\" as const;\n\n constructor() {\n super({\n message: \"File manager settings not found.\"\n });\n }\n}\n\nexport class SettingsNotAuthorizedError extends BaseError {\n override readonly code = \"FileManager/Settings/NotAuthorizedError\" as const;\n\n constructor() {\n super({\n message: \"Not authorized.\"\n });\n }\n}\n\nexport class SettingsUpdateError extends BaseError {\n override readonly code = \"FileManager/Settings/UpdateError\" as const;\n\n constructor(error: Error) {\n super({\n message: `Error updating settings: ${error.message}`\n });\n }\n}\n\ninterface ValidationParams {\n invalidFields: OutputErrors;\n}\n\nexport class SettingsValidationError extends BaseError<ValidationParams> {\n override readonly code = \"FileManager/Settings/ValidationError\" as const;\n\n constructor(invalidFields: OutputErrors) {\n super({\n message: \"Validation failed.\",\n data: { invalidFields }\n });\n }\n}\n"],"names":["SettingsNotFoundError","BaseError","SettingsNotAuthorizedError","SettingsUpdateError","error","SettingsValidationError","invalidFields"],"mappings":";AAGO,MAAMA,8BAA8BC;IAGvC,aAAc;QACV,KAAK,CAAC;YACF,SAAS;QACb,SALc,IAAI,GAAG;IAMzB;AACJ;AAEO,MAAMC,mCAAmCD;IAG5C,aAAc;QACV,KAAK,CAAC;YACF,SAAS;QACb,SALc,IAAI,GAAG;IAMzB;AACJ;AAEO,MAAME,4BAA4BF;IAGrC,YAAYG,KAAY,CAAE;QACtB,KAAK,CAAC;YACF,SAAS,CAAC,yBAAyB,EAAEA,MAAM,OAAO,EAAE;QACxD,SALc,IAAI,GAAG;IAMzB;AACJ;AAMO,MAAMC,gCAAgCJ;IAGzC,YAAYK,aAA2B,CAAE;QACrC,KAAK,CAAC;YACF,SAAS;YACT,MAAM;gBAAEA;YAAc;QAC1B,SANc,IAAI,GAAG;IAOzB;AACJ"}
@@ -2,5 +2,13 @@ import zod from "zod";
2
2
  export declare const updateSettingsValidation: zod.ZodObject<{
3
3
  uploadMinFileSize: zod.ZodOptional<zod.ZodPipe<zod.ZodOptional<zod.ZodNullable<zod.ZodNumber>>, zod.ZodTransform<number, number | null | undefined>>>;
4
4
  uploadMaxFileSize: zod.ZodOptional<zod.ZodPipe<zod.ZodOptional<zod.ZodNullable<zod.ZodNumber>>, zod.ZodTransform<number, number | null | undefined>>>;
5
- srcPrefix: zod.ZodPipe<zod.ZodOptional<zod.ZodString>, zod.ZodTransform<string, string | undefined>>;
5
+ srcPrefix: zod.ZodOptional<zod.ZodPipe<zod.ZodString, zod.ZodTransform<string, string>>>;
6
+ }, zod.core.$strip>;
7
+ /**
8
+ * Validates the settings after the input has been merged with the stored settings,
9
+ * so rules that span fields also hold for partial updates.
10
+ */
11
+ export declare const mergedSettingsValidation: zod.ZodObject<{
12
+ uploadMinFileSize: zod.ZodNumber;
13
+ uploadMaxFileSize: zod.ZodNumber;
6
14
  }, zod.core.$strip>;
@@ -4,24 +4,46 @@ const MIN_FILE_SIZE = 0;
4
4
  const MAX_FILE_SIZE = 10737418240;
5
5
  const uploadMinFileSizeValidation = zod.number().min(MIN_FILE_SIZE, {
6
6
  message: `Value needs to be greater than or equal to ${MIN_FILE_SIZE}.`
7
+ }).max(MAX_FILE_SIZE, {
8
+ message: `Value needs to be lesser than or equal to ${MAX_FILE_SIZE}.`
7
9
  }).nullish().transform((value)=>value || MIN_FILE_SIZE).optional();
8
10
  const uploadMaxFileSizeValidation = zod.number().max(MAX_FILE_SIZE, {
9
11
  message: `Value needs to be lesser than or equal to ${MAX_FILE_SIZE}.`
10
12
  }).nullish().transform((value)=>value || MAX_FILE_SIZE).optional();
13
+ const isHttpUrl = (value)=>{
14
+ try {
15
+ const url = new URL(value);
16
+ return "https:" === url.protocol || "http:" === url.protocol;
17
+ } catch {
18
+ return false;
19
+ }
20
+ };
21
+ const withTrailingSlash = (value)=>value.endsWith("/") ? value : value + "/";
22
+ const srcPrefixValidation = zod.string().refine((value)=>!value || isHttpUrl(value), {
23
+ message: "Value needs to be an absolute http(s) URL."
24
+ }).transform(async (value)=>{
25
+ if (!value) {
26
+ const manifest = await ServiceDiscovery.load();
27
+ const domain = manifest?.api?.cloudfront?.domain;
28
+ if (!domain) return "";
29
+ return withTrailingSlash(`${domain}/files`);
30
+ }
31
+ return withTrailingSlash(value);
32
+ }).optional();
11
33
  const updateSettingsValidation = zod.object({
12
34
  uploadMinFileSize: uploadMinFileSizeValidation,
13
35
  uploadMaxFileSize: uploadMaxFileSizeValidation,
14
- srcPrefix: zod.string().optional().transform(async (value)=>{
15
- if (!value) {
16
- const manifest = await ServiceDiscovery.load();
17
- if (!manifest || !manifest.api) return "";
18
- const { domain } = manifest.api.cloudfront;
19
- return `https://${domain}/files/`;
20
- }
21
- if ("string" == typeof value) return value.endsWith("/") ? value : value + "/";
22
- return value;
23
- })
36
+ srcPrefix: srcPrefixValidation
37
+ });
38
+ const mergedSettingsValidation = zod.object({
39
+ uploadMinFileSize: zod.number(),
40
+ uploadMaxFileSize: zod.number()
41
+ }).refine((settings)=>settings.uploadMinFileSize <= settings.uploadMaxFileSize, {
42
+ path: [
43
+ "uploadMinFileSize"
44
+ ],
45
+ message: "Value needs to be lesser than or equal to the maximum file upload size."
24
46
  });
25
- export { updateSettingsValidation };
47
+ export { mergedSettingsValidation, updateSettingsValidation };
26
48
 
27
49
  //# sourceMappingURL=validation.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"domain/settings/validation.js","sources":["../../../src/domain/settings/validation.ts"],"sourcesContent":["import zod from \"zod\";\nimport { ServiceDiscovery } from \"@webiny/api-core/features/serviceDiscovery/index.js\";\n\nconst MIN_FILE_SIZE = 0;\nconst MAX_FILE_SIZE = 10737418240;\n\nconst uploadMinFileSizeValidation = zod\n .number()\n .min(MIN_FILE_SIZE, {\n message: `Value needs to be greater than or equal to ${MIN_FILE_SIZE}.`\n })\n .nullish()\n .transform(value => {\n return value || MIN_FILE_SIZE;\n })\n .optional();\n\nconst uploadMaxFileSizeValidation = zod\n .number()\n .max(MAX_FILE_SIZE, {\n message: `Value needs to be lesser than or equal to ${MAX_FILE_SIZE}.`\n })\n .nullish()\n .transform(value => {\n return value || MAX_FILE_SIZE;\n })\n .optional();\n\nexport const updateSettingsValidation = zod.object({\n uploadMinFileSize: uploadMinFileSizeValidation,\n uploadMaxFileSize: uploadMaxFileSizeValidation,\n srcPrefix: zod\n .string()\n .optional()\n .transform(async value => {\n if (!value) {\n const manifest = await ServiceDiscovery.load();\n if (!manifest || !manifest.api) {\n return \"\";\n }\n\n const { domain } = manifest.api.cloudfront;\n\n return `https://${domain}/files/`;\n }\n if (typeof value === \"string\") {\n return value.endsWith(\"/\") ? value : value + \"/\";\n }\n return value;\n })\n});\n"],"names":["MIN_FILE_SIZE","MAX_FILE_SIZE","uploadMinFileSizeValidation","zod","value","uploadMaxFileSizeValidation","updateSettingsValidation","manifest","ServiceDiscovery","domain"],"mappings":";;AAGA,MAAMA,gBAAgB;AACtB,MAAMC,gBAAgB;AAEtB,MAAMC,8BAA8BC,IAAAA,MACzB,GACN,GAAG,CAACH,eAAe;IAChB,SAAS,CAAC,2CAA2C,EAAEA,cAAc,CAAC,CAAC;AAC3E,GACC,OAAO,GACP,SAAS,CAACI,CAAAA,QACAA,SAASJ,eAEnB,QAAQ;AAEb,MAAMK,8BAA8BF,IAAAA,MACzB,GACN,GAAG,CAACF,eAAe;IAChB,SAAS,CAAC,0CAA0C,EAAEA,cAAc,CAAC,CAAC;AAC1E,GACC,OAAO,GACP,SAAS,CAACG,CAAAA,QACAA,SAASH,eAEnB,QAAQ;AAEN,MAAMK,2BAA2BH,IAAI,MAAM,CAAC;IAC/C,mBAAmBD;IACnB,mBAAmBG;IACnB,WAAWF,IAAAA,MACA,GACN,QAAQ,GACR,SAAS,CAAC,OAAMC;QACb,IAAI,CAACA,OAAO;YACR,MAAMG,WAAW,MAAMC,iBAAiB,IAAI;YAC5C,IAAI,CAACD,YAAY,CAACA,SAAS,GAAG,EAC1B,OAAO;YAGX,MAAM,EAAEE,MAAM,EAAE,GAAGF,SAAS,GAAG,CAAC,UAAU;YAE1C,OAAO,CAAC,QAAQ,EAAEE,OAAO,OAAO,CAAC;QACrC;QACA,IAAI,AAAiB,YAAjB,OAAOL,OACP,OAAOA,MAAM,QAAQ,CAAC,OAAOA,QAAQA,QAAQ;QAEjD,OAAOA;IACX;AACR"}
1
+ {"version":3,"file":"domain/settings/validation.js","sources":["../../../src/domain/settings/validation.ts"],"sourcesContent":["import zod from \"zod\";\nimport { ServiceDiscovery } from \"@webiny/api-core/features/serviceDiscovery/index.js\";\n\nconst MIN_FILE_SIZE = 0;\nconst MAX_FILE_SIZE = 10737418240;\n\nconst uploadMinFileSizeValidation = zod\n .number()\n .min(MIN_FILE_SIZE, {\n message: `Value needs to be greater than or equal to ${MIN_FILE_SIZE}.`\n })\n .max(MAX_FILE_SIZE, {\n message: `Value needs to be lesser than or equal to ${MAX_FILE_SIZE}.`\n })\n .nullish()\n .transform(value => {\n return value || MIN_FILE_SIZE;\n })\n .optional();\n\nconst uploadMaxFileSizeValidation = zod\n .number()\n .max(MAX_FILE_SIZE, {\n message: `Value needs to be lesser than or equal to ${MAX_FILE_SIZE}.`\n })\n .nullish()\n .transform(value => {\n return value || MAX_FILE_SIZE;\n })\n .optional();\n\nconst isHttpUrl = (value: string): boolean => {\n try {\n const url = new URL(value);\n return url.protocol === \"https:\" || url.protocol === \"http:\";\n } catch {\n return false;\n }\n};\n\nconst withTrailingSlash = (value: string): string => {\n return value.endsWith(\"/\") ? value : value + \"/\";\n};\n\n/**\n * `optional()` wraps the transform, so a missing `srcPrefix` stays missing\n * and a partial update keeps the stored value. An empty string falls back to the API's URL.\n */\nconst srcPrefixValidation = zod\n .string()\n .refine(value => !value || isHttpUrl(value), {\n message: \"Value needs to be an absolute http(s) URL.\"\n })\n .transform(async value => {\n if (!value) {\n const manifest = await ServiceDiscovery.load();\n const domain = manifest?.api?.cloudfront?.domain;\n if (!domain) {\n return \"\";\n }\n // The manifest domain already includes the protocol.\n return withTrailingSlash(`${domain}/files`);\n }\n return withTrailingSlash(value);\n })\n .optional();\n\nexport const updateSettingsValidation = zod.object({\n uploadMinFileSize: uploadMinFileSizeValidation,\n uploadMaxFileSize: uploadMaxFileSizeValidation,\n srcPrefix: srcPrefixValidation\n});\n\n/**\n * Validates the settings after the input has been merged with the stored settings,\n * so rules that span fields also hold for partial updates.\n */\nexport const mergedSettingsValidation = zod\n .object({\n uploadMinFileSize: zod.number(),\n uploadMaxFileSize: zod.number()\n })\n .refine(settings => settings.uploadMinFileSize <= settings.uploadMaxFileSize, {\n path: [\"uploadMinFileSize\"],\n message: \"Value needs to be lesser than or equal to the maximum file upload size.\"\n });\n"],"names":["MIN_FILE_SIZE","MAX_FILE_SIZE","uploadMinFileSizeValidation","zod","value","uploadMaxFileSizeValidation","isHttpUrl","url","URL","withTrailingSlash","srcPrefixValidation","manifest","ServiceDiscovery","domain","updateSettingsValidation","mergedSettingsValidation","settings"],"mappings":";;AAGA,MAAMA,gBAAgB;AACtB,MAAMC,gBAAgB;AAEtB,MAAMC,8BAA8BC,IAAAA,MACzB,GACN,GAAG,CAACH,eAAe;IAChB,SAAS,CAAC,2CAA2C,EAAEA,cAAc,CAAC,CAAC;AAC3E,GACC,GAAG,CAACC,eAAe;IAChB,SAAS,CAAC,0CAA0C,EAAEA,cAAc,CAAC,CAAC;AAC1E,GACC,OAAO,GACP,SAAS,CAACG,CAAAA,QACAA,SAASJ,eAEnB,QAAQ;AAEb,MAAMK,8BAA8BF,IAAAA,MACzB,GACN,GAAG,CAACF,eAAe;IAChB,SAAS,CAAC,0CAA0C,EAAEA,cAAc,CAAC,CAAC;AAC1E,GACC,OAAO,GACP,SAAS,CAACG,CAAAA,QACAA,SAASH,eAEnB,QAAQ;AAEb,MAAMK,YAAY,CAACF;IACf,IAAI;QACA,MAAMG,MAAM,IAAIC,IAAIJ;QACpB,OAAOG,AAAiB,aAAjBA,IAAI,QAAQ,IAAiBA,AAAiB,YAAjBA,IAAI,QAAQ;IACpD,EAAE,OAAM;QACJ,OAAO;IACX;AACJ;AAEA,MAAME,oBAAoB,CAACL,QAChBA,MAAM,QAAQ,CAAC,OAAOA,QAAQA,QAAQ;AAOjD,MAAMM,sBAAsBP,IAAAA,MACjB,GACN,MAAM,CAACC,CAAAA,QAAS,CAACA,SAASE,UAAUF,QAAQ;IACzC,SAAS;AACb,GACC,SAAS,CAAC,OAAMA;IACb,IAAI,CAACA,OAAO;QACR,MAAMO,WAAW,MAAMC,iBAAiB,IAAI;QAC5C,MAAMC,SAASF,UAAU,KAAK,YAAY;QAC1C,IAAI,CAACE,QACD,OAAO;QAGX,OAAOJ,kBAAkB,GAAGI,OAAO,MAAM,CAAC;IAC9C;IACA,OAAOJ,kBAAkBL;AAC7B,GACC,QAAQ;AAEN,MAAMU,2BAA2BX,IAAI,MAAM,CAAC;IAC/C,mBAAmBD;IACnB,mBAAmBG;IACnB,WAAWK;AACf;AAMO,MAAMK,2BAA2BZ,IAAAA,MAC7B,CAAC;IACJ,mBAAmBA,IAAI,MAAM;IAC7B,mBAAmBA,IAAI,MAAM;AACjC,GACC,MAAM,CAACa,CAAAA,WAAYA,SAAS,iBAAiB,IAAIA,SAAS,iBAAiB,EAAE;IAC1E,MAAM;QAAC;KAAoB;IAC3B,SAAS;AACb"}
@@ -1,10 +1,18 @@
1
1
  import type { File } from "../../../domain/file/types.js";
2
2
  import { IdentityContext } from "@webiny/api-core/features/security/IdentityContext/index.js";
3
+ import { FmPermissions } from "../../../features/shared/abstractions.js";
3
4
  import { AssetAuthorizer } from "../abstractions/AssetAuthorizer.js";
5
+ /**
6
+ * Private files can only be read by identities with File Manager read access in the file's
7
+ * tenant. Being logged in is not enough: API keys (e.g. the public website key) and identities
8
+ * from other tenants are authenticated too.
9
+ */
4
10
  export declare class PrivateAuthenticatedAuthorizer implements AssetAuthorizer.Interface {
5
11
  private identityContext;
6
- constructor(identityContext: IdentityContext.Interface);
12
+ private permissions;
13
+ constructor(identityContext: IdentityContext.Interface, permissions: FmPermissions.Interface);
7
14
  authorize(file: File): Promise<void>;
15
+ private notAuthorized;
8
16
  }
9
17
  export declare const PrivateAuthenticatedAuthorizerImpl: typeof PrivateAuthenticatedAuthorizer & {
10
18
  __abstraction: import("@webiny/di").Abstraction<import("../abstractions/AssetAuthorizer.js").IAssetAuthorizer>;
@@ -1,24 +1,29 @@
1
1
  import error from "@webiny/error";
2
2
  import { IdentityContext } from "@webiny/api-core/features/security/IdentityContext/index.js";
3
+ import { FmPermissions } from "../../shared/abstractions.js";
3
4
  import { AssetAuthorizer } from "../abstractions/AssetAuthorizer.js";
4
5
  class PrivateAuthenticatedAuthorizer {
5
- constructor(identityContext){
6
+ constructor(identityContext, permissions){
6
7
  this.identityContext = identityContext;
8
+ this.permissions = permissions;
7
9
  }
8
10
  async authorize(file) {
9
- if (file.accessControl && "private-authenticated" === file.accessControl.type) {
10
- const identity = this.identityContext.getIdentity();
11
- if (!identity) throw new error({
12
- code: "NOT_AUTHORIZED",
13
- message: "You're not authorized to access this asset!"
14
- });
15
- }
11
+ if (file.accessControl?.type !== "private-authenticated") return;
12
+ if (this.identityContext.getIdentity().isAnonymous()) throw this.notAuthorized();
13
+ if (!await this.permissions.canRead("file")) throw this.notAuthorized();
14
+ }
15
+ notAuthorized() {
16
+ return new error({
17
+ code: "NOT_AUTHORIZED",
18
+ message: "You're not authorized to access this asset!"
19
+ });
16
20
  }
17
21
  }
18
22
  const PrivateAuthenticatedAuthorizerImpl = AssetAuthorizer.createImplementation({
19
23
  implementation: PrivateAuthenticatedAuthorizer,
20
24
  dependencies: [
21
- IdentityContext
25
+ IdentityContext,
26
+ FmPermissions
22
27
  ]
23
28
  });
24
29
  export { PrivateAuthenticatedAuthorizer, PrivateAuthenticatedAuthorizerImpl };
@@ -1 +1 @@
1
- {"version":3,"file":"features/assetDelivery/privateFiles/PrivateAuthenticatedAuthorizer.js","sources":["../../../../src/features/assetDelivery/privateFiles/PrivateAuthenticatedAuthorizer.ts"],"sourcesContent":["import Error from \"@webiny/error\";\nimport type { File } from \"~/domain/file/types.js\";\nimport { IdentityContext } from \"@webiny/api-core/features/security/IdentityContext/index.js\";\nimport { AssetAuthorizer } from \"../abstractions/AssetAuthorizer.js\";\n\nexport class PrivateAuthenticatedAuthorizer implements AssetAuthorizer.Interface {\n private identityContext: IdentityContext.Interface;\n\n constructor(identityContext: IdentityContext.Interface) {\n this.identityContext = identityContext;\n }\n\n async authorize(file: File) {\n if (file.accessControl && file.accessControl.type === \"private-authenticated\") {\n const identity = this.identityContext.getIdentity();\n\n if (!identity) {\n throw new Error({\n code: \"NOT_AUTHORIZED\",\n message: \"You're not authorized to access this asset!\"\n });\n }\n }\n }\n}\n\nexport const PrivateAuthenticatedAuthorizerImpl = AssetAuthorizer.createImplementation({\n implementation: PrivateAuthenticatedAuthorizer,\n dependencies: [IdentityContext]\n});\n"],"names":["PrivateAuthenticatedAuthorizer","identityContext","file","identity","Error","PrivateAuthenticatedAuthorizerImpl","AssetAuthorizer","IdentityContext"],"mappings":";;;AAKO,MAAMA;IAGT,YAAYC,eAA0C,CAAE;QACpD,IAAI,CAAC,eAAe,GAAGA;IAC3B;IAEA,MAAM,UAAUC,IAAU,EAAE;QACxB,IAAIA,KAAK,aAAa,IAAIA,AAA4B,4BAA5BA,KAAK,aAAa,CAAC,IAAI,EAA8B;YAC3E,MAAMC,WAAW,IAAI,CAAC,eAAe,CAAC,WAAW;YAEjD,IAAI,CAACA,UACD,MAAM,IAAIC,MAAM;gBACZ,MAAM;gBACN,SAAS;YACb;QAER;IACJ;AACJ;AAEO,MAAMC,qCAAqCC,gBAAgB,oBAAoB,CAAC;IACnF,gBAAgBN;IAChB,cAAc;QAACO;KAAgB;AACnC"}
1
+ {"version":3,"file":"features/assetDelivery/privateFiles/PrivateAuthenticatedAuthorizer.js","sources":["../../../../src/features/assetDelivery/privateFiles/PrivateAuthenticatedAuthorizer.ts"],"sourcesContent":["import Error from \"@webiny/error\";\nimport type { File } from \"~/domain/file/types.js\";\nimport { IdentityContext } from \"@webiny/api-core/features/security/IdentityContext/index.js\";\nimport { FmPermissions } from \"~/features/shared/abstractions.js\";\nimport { AssetAuthorizer } from \"../abstractions/AssetAuthorizer.js\";\n\n/**\n * Private files can only be read by identities with File Manager read access in the file's\n * tenant. Being logged in is not enough: API keys (e.g. the public website key) and identities\n * from other tenants are authenticated too.\n */\nexport class PrivateAuthenticatedAuthorizer implements AssetAuthorizer.Interface {\n private identityContext: IdentityContext.Interface;\n private permissions: FmPermissions.Interface;\n\n constructor(identityContext: IdentityContext.Interface, permissions: FmPermissions.Interface) {\n this.identityContext = identityContext;\n this.permissions = permissions;\n }\n\n async authorize(file: File) {\n if (file.accessControl?.type !== \"private-authenticated\") {\n return;\n }\n\n if (this.identityContext.getIdentity().isAnonymous()) {\n throw this.notAuthorized();\n }\n\n if (!(await this.permissions.canRead(\"file\"))) {\n throw this.notAuthorized();\n }\n }\n\n private notAuthorized() {\n return new Error({\n code: \"NOT_AUTHORIZED\",\n message: \"You're not authorized to access this asset!\"\n });\n }\n}\n\nexport const PrivateAuthenticatedAuthorizerImpl = AssetAuthorizer.createImplementation({\n implementation: PrivateAuthenticatedAuthorizer,\n dependencies: [IdentityContext, FmPermissions]\n});\n"],"names":["PrivateAuthenticatedAuthorizer","identityContext","permissions","file","Error","PrivateAuthenticatedAuthorizerImpl","AssetAuthorizer","IdentityContext","FmPermissions"],"mappings":";;;;AAWO,MAAMA;IAIT,YAAYC,eAA0C,EAAEC,WAAoC,CAAE;QAC1F,IAAI,CAAC,eAAe,GAAGD;QACvB,IAAI,CAAC,WAAW,GAAGC;IACvB;IAEA,MAAM,UAAUC,IAAU,EAAE;QACxB,IAAIA,KAAK,aAAa,EAAE,SAAS,yBAC7B;QAGJ,IAAI,IAAI,CAAC,eAAe,CAAC,WAAW,GAAG,WAAW,IAC9C,MAAM,IAAI,CAAC,aAAa;QAG5B,IAAI,CAAE,MAAM,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,SACjC,MAAM,IAAI,CAAC,aAAa;IAEhC;IAEQ,gBAAgB;QACpB,OAAO,IAAIC,MAAM;YACb,MAAM;YACN,SAAS;QACb;IACJ;AACJ;AAEO,MAAMC,qCAAqCC,gBAAgB,oBAAoB,CAAC;IACnF,gBAAgBN;IAChB,cAAc;QAACO;QAAiBC;KAAc;AAClD"}
@@ -3,7 +3,7 @@ import { CreateFileRepository } from "./abstractions.js";
3
3
  import { CreateEntryUseCase } from "@webiny/api-headless-cms/features/contentEntry/CreateEntry";
4
4
  import { FileModel } from "../../../domain/file/abstractions.js";
5
5
  import { EntryToFileMapper } from "../shared/EntryToFileMapper.js";
6
- import { FileNotAuthorizedError, FilePersistenceError } from "../../../domain/file/errors.js";
6
+ import { FileAlreadyExistsError, FileNotAuthorizedError, FilePersistenceError } from "../../../domain/file/errors.js";
7
7
  import { FileInputToEntryInputMapper } from "../shared/FileInputToEntryInputMapper.js";
8
8
  class CreateFileRepositoryImpl {
9
9
  constructor(createEntry, fileModel){
@@ -11,9 +11,15 @@ class CreateFileRepositoryImpl {
11
11
  this.fileModel = fileModel;
12
12
  }
13
13
  async execute(data) {
14
- const result = await this.createEntry.execute(this.fileModel, FileInputToEntryInputMapper.toEntry(data));
14
+ const result = await this.createEntry.execute(this.fileModel, FileInputToEntryInputMapper.toEntry(data), {
15
+ failIfExists: true
16
+ });
15
17
  if (result.isFail()) {
16
18
  if ("Cms/Entry/NotAuthorized" === result.error.code) return Result.fail(new FileNotAuthorizedError());
19
+ if ("Cms/Entry/AlreadyExists" === result.error.code) return Result.fail(new FileAlreadyExistsError({
20
+ key: data.key,
21
+ id: data.id
22
+ }));
17
23
  return Result.fail(new FilePersistenceError(result.error));
18
24
  }
19
25
  const file = EntryToFileMapper.toFile(result.value);
@@ -1 +1 @@
1
- {"version":3,"file":"features/file/CreateFile/CreateFileRepository.js","sources":["../../../../src/features/file/CreateFile/CreateFileRepository.ts"],"sourcesContent":["import { Result } from \"@webiny/feature/api\";\nimport { CreateFileRepository as RepositoryAbstraction } from \"./abstractions.js\";\nimport { CreateEntryUseCase } from \"@webiny/api-headless-cms/features/contentEntry/CreateEntry\";\nimport { FileModel } from \"~/domain/file/abstractions.js\";\nimport type { File, FileInput } from \"~/domain/file/types.js\";\nimport { EntryToFileMapper } from \"../shared/EntryToFileMapper.js\";\nimport { FileNotAuthorizedError, FilePersistenceError } from \"~/domain/file/errors.js\";\nimport { FileInputToEntryInputMapper } from \"~/features/file/shared/FileInputToEntryInputMapper.js\";\n\nclass CreateFileRepositoryImpl implements RepositoryAbstraction.Interface {\n constructor(\n private createEntry: CreateEntryUseCase.Interface,\n private fileModel: FileModel.Interface\n ) {}\n\n async execute(data: FileInput): Promise<Result<File, RepositoryAbstraction.Error>> {\n const result = await this.createEntry.execute(\n this.fileModel,\n FileInputToEntryInputMapper.toEntry(data)\n );\n\n if (result.isFail()) {\n if (result.error.code === \"Cms/Entry/NotAuthorized\") {\n return Result.fail(new FileNotAuthorizedError());\n }\n\n return Result.fail(new FilePersistenceError(result.error));\n }\n\n const file = EntryToFileMapper.toFile(result.value);\n return Result.ok(file);\n }\n}\n\nexport const CreateFileRepository = RepositoryAbstraction.createImplementation({\n implementation: CreateFileRepositoryImpl,\n dependencies: [CreateEntryUseCase, FileModel]\n});\n"],"names":["CreateFileRepositoryImpl","createEntry","fileModel","data","result","FileInputToEntryInputMapper","Result","FileNotAuthorizedError","FilePersistenceError","file","EntryToFileMapper","CreateFileRepository","RepositoryAbstraction","CreateEntryUseCase","FileModel"],"mappings":";;;;;;;AASA,MAAMA;IACF,YACYC,WAAyC,EACzCC,SAA8B,CACxC;aAFUD,WAAW,GAAXA;aACAC,SAAS,GAATA;IACT;IAEH,MAAM,QAAQC,IAAe,EAAsD;QAC/E,MAAMC,SAAS,MAAM,IAAI,CAAC,WAAW,CAAC,OAAO,CACzC,IAAI,CAAC,SAAS,EACdC,4BAA4B,OAAO,CAACF;QAGxC,IAAIC,OAAO,MAAM,IAAI;YACjB,IAAIA,AAAsB,8BAAtBA,OAAO,KAAK,CAAC,IAAI,EACjB,OAAOE,OAAO,IAAI,CAAC,IAAIC;YAG3B,OAAOD,OAAO,IAAI,CAAC,IAAIE,qBAAqBJ,OAAO,KAAK;QAC5D;QAEA,MAAMK,OAAOC,kBAAkB,MAAM,CAACN,OAAO,KAAK;QAClD,OAAOE,OAAO,EAAE,CAACG;IACrB;AACJ;AAEO,MAAME,4CAAuBC,qBAAAA,oBAA0C,CAAC;IAC3E,gBAAgBZ;IAChB,cAAc;QAACa;QAAoBC;KAAU;AACjD"}
1
+ {"version":3,"file":"features/file/CreateFile/CreateFileRepository.js","sources":["../../../../src/features/file/CreateFile/CreateFileRepository.ts"],"sourcesContent":["import { Result } from \"@webiny/feature/api\";\nimport { CreateFileRepository as RepositoryAbstraction } from \"./abstractions.js\";\nimport { CreateEntryUseCase } from \"@webiny/api-headless-cms/features/contentEntry/CreateEntry\";\nimport { FileModel } from \"~/domain/file/abstractions.js\";\nimport type { File, FileInput } from \"~/domain/file/types.js\";\nimport { EntryToFileMapper } from \"../shared/EntryToFileMapper.js\";\nimport {\n FileAlreadyExistsError,\n FileNotAuthorizedError,\n FilePersistenceError\n} from \"~/domain/file/errors.js\";\nimport { FileInputToEntryInputMapper } from \"~/features/file/shared/FileInputToEntryInputMapper.js\";\n\nclass CreateFileRepositoryImpl implements RepositoryAbstraction.Interface {\n constructor(\n private createEntry: CreateEntryUseCase.Interface,\n private fileModel: FileModel.Interface\n ) {}\n\n async execute(data: FileInput): Promise<Result<File, RepositoryAbstraction.Error>> {\n const result = await this.createEntry.execute(\n this.fileModel,\n FileInputToEntryInputMapper.toEntry(data),\n // A client may choose the file id; it must not replace an existing file.\n { failIfExists: true }\n );\n\n if (result.isFail()) {\n if (result.error.code === \"Cms/Entry/NotAuthorized\") {\n return Result.fail(new FileNotAuthorizedError());\n }\n if (result.error.code === \"Cms/Entry/AlreadyExists\") {\n return Result.fail(new FileAlreadyExistsError({ key: data.key, id: data.id }));\n }\n\n return Result.fail(new FilePersistenceError(result.error));\n }\n\n const file = EntryToFileMapper.toFile(result.value);\n return Result.ok(file);\n }\n}\n\nexport const CreateFileRepository = RepositoryAbstraction.createImplementation({\n implementation: CreateFileRepositoryImpl,\n dependencies: [CreateEntryUseCase, FileModel]\n});\n"],"names":["CreateFileRepositoryImpl","createEntry","fileModel","data","result","FileInputToEntryInputMapper","Result","FileNotAuthorizedError","FileAlreadyExistsError","FilePersistenceError","file","EntryToFileMapper","CreateFileRepository","RepositoryAbstraction","CreateEntryUseCase","FileModel"],"mappings":";;;;;;;AAaA,MAAMA;IACF,YACYC,WAAyC,EACzCC,SAA8B,CACxC;aAFUD,WAAW,GAAXA;aACAC,SAAS,GAATA;IACT;IAEH,MAAM,QAAQC,IAAe,EAAsD;QAC/E,MAAMC,SAAS,MAAM,IAAI,CAAC,WAAW,CAAC,OAAO,CACzC,IAAI,CAAC,SAAS,EACdC,4BAA4B,OAAO,CAACF,OAEpC;YAAE,cAAc;QAAK;QAGzB,IAAIC,OAAO,MAAM,IAAI;YACjB,IAAIA,AAAsB,8BAAtBA,OAAO,KAAK,CAAC,IAAI,EACjB,OAAOE,OAAO,IAAI,CAAC,IAAIC;YAE3B,IAAIH,AAAsB,8BAAtBA,OAAO,KAAK,CAAC,IAAI,EACjB,OAAOE,OAAO,IAAI,CAAC,IAAIE,uBAAuB;gBAAE,KAAKL,KAAK,GAAG;gBAAE,IAAIA,KAAK,EAAE;YAAC;YAG/E,OAAOG,OAAO,IAAI,CAAC,IAAIG,qBAAqBL,OAAO,KAAK;QAC5D;QAEA,MAAMM,OAAOC,kBAAkB,MAAM,CAACP,OAAO,KAAK;QAClD,OAAOE,OAAO,EAAE,CAACI;IACrB;AACJ;AAEO,MAAME,4CAAuBC,qBAAAA,oBAA0C,CAAC;IAC3E,gBAAgBb;IAChB,cAAc;QAACc;QAAoBC;KAAU;AACjD"}
@@ -2,11 +2,12 @@ import { Result } from "@webiny/feature/api";
2
2
  import { CreateFileRepository, CreateFileUseCase } from "./abstractions.js";
3
3
  import { GetSettingsUseCase } from "../../settings/GetSettings/abstractions.js";
4
4
  import { EventPublisher } from "@webiny/api-core/features/eventPublisher/index.js";
5
- import { FileNotAuthorizedError, InvalidFileSizeError } from "../../../domain/file/errors.js";
5
+ import { FileNotAuthorizedError, InvalidFileKeyError, InvalidFileSizeError } from "../../../domain/file/errors.js";
6
6
  import { FileAfterCreateEvent, FileBeforeCreateEvent } from "./events.js";
7
7
  import { FmPermissions } from "../../shared/abstractions.js";
8
8
  import { IdentityContext } from "@webiny/api-core/features/security/IdentityContext/index.js";
9
9
  import { Identity } from "../../../domain/identity/Identity.js";
10
+ import { isValidFileKey } from "../shared/isValidFileKey.js";
10
11
  class CreateFileUseCaseImpl {
11
12
  constructor(identityContext, permissions, repository, getSettings, eventPublisher){
12
13
  this.identityContext = identityContext;
@@ -21,9 +22,15 @@ class CreateFileUseCaseImpl {
21
22
  const validationResult = await this.validateInput(input);
22
23
  if (validationResult.isFail()) return Result.fail(validationResult.error);
23
24
  const [id] = input.key.split("/");
25
+ const fileId = input.id || id;
26
+ if (this.identityContext.isAuthorizationEnabled() && !isValidFileKey(fileId, input.key)) return Result.fail(new InvalidFileKeyError({
27
+ id: fileId,
28
+ key: input.key
29
+ }));
24
30
  const currentIdentity = this.identityContext.getIdentity();
31
+ const systemInput = !this.identityContext.isAuthorizationEnabled() || await this.identityContext.hasFullAccess() ? input : {};
25
32
  const fileInput = {
26
- id: input.id || id,
33
+ id: fileId,
27
34
  key: input.key,
28
35
  name: input.name,
29
36
  size: input.size,
@@ -35,12 +42,12 @@ class CreateFileUseCaseImpl {
35
42
  tags: input.tags || [],
36
43
  description: input.description ?? "",
37
44
  extensions: meta || {},
38
- createdOn: input.createdOn,
39
- modifiedOn: input.modifiedOn,
40
- savedOn: input.savedOn,
41
- createdBy: input.createdBy ? Identity.from(input.createdBy) : Identity.from(currentIdentity),
42
- modifiedBy: input.modifiedBy ? Identity.from(input.modifiedBy) : void 0,
43
- savedBy: input.savedBy ? Identity.from(input.savedBy) : Identity.from(currentIdentity)
45
+ createdOn: systemInput.createdOn,
46
+ modifiedOn: systemInput.modifiedOn,
47
+ savedOn: systemInput.savedOn,
48
+ createdBy: systemInput.createdBy ? Identity.from(systemInput.createdBy) : Identity.from(currentIdentity),
49
+ modifiedBy: systemInput.modifiedBy ? Identity.from(systemInput.modifiedBy) : void 0,
50
+ savedBy: systemInput.savedBy ? Identity.from(systemInput.savedBy) : Identity.from(currentIdentity)
44
51
  };
45
52
  await this.eventPublisher.publish(new FileBeforeCreateEvent({
46
53
  file: fileInput,
@@ -1 +1 @@
1
- {"version":3,"file":"features/file/CreateFile/CreateFileUseCase.js","sources":["../../../../src/features/file/CreateFile/CreateFileUseCase.ts"],"sourcesContent":["import { Result } from \"@webiny/feature/api\";\nimport {\n CreateFileUseCase as UseCaseAbstraction,\n CreateFileInput,\n CreateFileRepository\n} from \"./abstractions.js\";\nimport { GetSettingsUseCase } from \"../../settings/GetSettings/abstractions.js\";\nimport { EventPublisher } from \"@webiny/api-core/features/eventPublisher/index.js\";\nimport type { File, FileInput } from \"~/domain/file/types.js\";\nimport { FileNotAuthorizedError, InvalidFileSizeError } from \"~/domain/file/errors.js\";\nimport { FileBeforeCreateEvent, FileAfterCreateEvent } from \"./events.js\";\nimport { FmPermissions } from \"~/features/shared/abstractions.js\";\nimport { IdentityContext } from \"@webiny/api-core/features/security/IdentityContext/index.js\";\nimport { Identity } from \"~/domain/identity/Identity.js\";\n\nclass CreateFileUseCaseImpl implements UseCaseAbstraction.Interface {\n constructor(\n private identityContext: IdentityContext.Interface,\n private permissions: FmPermissions.Interface,\n private repository: CreateFileRepository.Interface,\n private getSettings: GetSettingsUseCase.Interface,\n private eventPublisher: EventPublisher.Interface\n ) {}\n\n async execute(\n input: CreateFileInput,\n meta?: Record<string, any>\n ): Promise<Result<File, UseCaseAbstraction.Error>> {\n const hasPermission = await this.permissions.canCreate(\"file\");\n if (!hasPermission) {\n return Result.fail(new FileNotAuthorizedError());\n }\n\n const validationResult = await this.validateInput(input);\n if (validationResult.isFail()) {\n return Result.fail(validationResult.error);\n }\n\n const [id] = input.key.split(\"/\");\n const currentIdentity = this.identityContext.getIdentity();\n\n // Prepare file input\n const fileInput: FileInput = {\n id: input.id || id,\n key: input.key,\n name: input.name,\n size: input.size,\n type: input.type,\n metadata: input.metadata || {},\n location: input.location || { folderId: \"root\" },\n tags: input.tags || [],\n description: input.description ?? \"\",\n extensions: meta || {},\n // system attributes\n createdOn: input.createdOn,\n modifiedOn: input.modifiedOn,\n savedOn: input.savedOn,\n createdBy: input.createdBy\n ? Identity.from(input.createdBy)\n : Identity.from(currentIdentity),\n modifiedBy: input.modifiedBy ? Identity.from(input.modifiedBy) : undefined,\n savedBy: input.savedBy ? Identity.from(input.savedBy) : Identity.from(currentIdentity)\n };\n\n await this.eventPublisher.publish(new FileBeforeCreateEvent({ file: fileInput, meta }));\n\n const result = await this.repository.execute(fileInput);\n\n if (result.isFail()) {\n return Result.fail(result.error);\n }\n\n await this.eventPublisher.publish(new FileAfterCreateEvent({ file: result.value, meta }));\n\n return Result.ok(result.value);\n }\n\n private async validateInput(\n input: CreateFileInput\n ): Promise<Result<void, InvalidFileSizeError>> {\n const settingsResult = await this.getSettings.execute();\n\n if (settingsResult.isFail()) {\n return Result.ok();\n }\n\n const settings = settingsResult.value;\n\n if (settings) {\n // Validate file size\n if (\n input.size < settings.uploadMinFileSize ||\n input.size > settings.uploadMaxFileSize\n ) {\n return Result.fail(\n new InvalidFileSizeError({\n size: input.size,\n minSize: settings.uploadMinFileSize,\n maxSize: settings.uploadMaxFileSize\n })\n );\n }\n }\n\n return Result.ok();\n }\n}\n\nexport const CreateFileUseCase = UseCaseAbstraction.createImplementation({\n implementation: CreateFileUseCaseImpl,\n dependencies: [\n IdentityContext,\n FmPermissions,\n CreateFileRepository,\n GetSettingsUseCase,\n EventPublisher\n ]\n});\n"],"names":["CreateFileUseCaseImpl","identityContext","permissions","repository","getSettings","eventPublisher","input","meta","hasPermission","Result","FileNotAuthorizedError","validationResult","id","currentIdentity","fileInput","Identity","undefined","FileBeforeCreateEvent","result","FileAfterCreateEvent","settingsResult","settings","InvalidFileSizeError","CreateFileUseCase","UseCaseAbstraction","IdentityContext","FmPermissions","CreateFileRepository","GetSettingsUseCase","EventPublisher"],"mappings":";;;;;;;;;AAeA,MAAMA;IACF,YACYC,eAA0C,EAC1CC,WAAoC,EACpCC,UAA0C,EAC1CC,WAAyC,EACzCC,cAAwC,CAClD;aALUJ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BAAsB;YAAE,MAAMH;YAAWP;QAAK;QAEpF,MAAMW,SAAS,MAAM,IAAI,CAAC,UAAU,CAAC,OAAO,CAACJ;QAE7C,IAAII,OAAO,MAAM,IACb,OAAOT,OAAO,IAAI,CAACS,OAAO,KAAK;QAGnC,MAAM,IAAI,CAAC,cAAc,CAAC,OAAO,CAAC,IAAIC,qBAAqB;YAAE,MAAMD,OAAO,KAAK;YAAEX;QAAK;QAEtF,OAAOE,OAAO,EAAE,CAACS,OAAO,KAAK;IACjC;IAEA,MAAc,cACVZ,KAAsB,EACqB;QAC3C,MAAMc,iBAAiB,MAAM,IAAI,CAAC,WAAW,CAAC,OAAO;QAErD,IAAIA,eAAe,MAAM,IACrB,OAAOX,OAAO,EAAE;QAGpB,MAAMY,WAAWD,eAAe,KAAK;QAErC,IAAIC,UAEA;YAAA,IACIf,MAAM,IAAI,GAAGe,SAAS,iBAAiB,IACvCf,MAAM,IAAI,GAAGe,SAAS,iBAAiB,EAEvC,OAAOZ,OAAO,IAAI,CACd,IAAIa,qBAAqB;gBACrB,MAAMhB,MAAM,IAAI;gBAChB,SAASe,SAAS,iBAAiB;gBACnC,SAASA,SAAS,iBAAiB;YACvC;QAER;QAGJ,OAAOZ,OAAO,EAAE;IACpB;AACJ;AAEO,MAAMc,sCAAoBC,kBAAAA,oBAAuC,CAAC;IACrE,gBAAgBxB;IAChB,cAAc;QACVyB;QACAC;QACAC;QACAC;QACAC;KACH;AACL"}
1
+ {"version":3,"file":"features/file/CreateFile/CreateFileUseCase.js","sources":["../../../../src/features/file/CreateFile/CreateFileUseCase.ts"],"sourcesContent":["import { Result } from \"@webiny/feature/api\";\nimport {\n CreateFileUseCase as UseCaseAbstraction,\n CreateFileInput,\n CreateFileRepository\n} from \"./abstractions.js\";\nimport { GetSettingsUseCase } from \"../../settings/GetSettings/abstractions.js\";\nimport { EventPublisher } from \"@webiny/api-core/features/eventPublisher/index.js\";\nimport type { File, FileInput } from \"~/domain/file/types.js\";\nimport {\n FileNotAuthorizedError,\n InvalidFileKeyError,\n InvalidFileSizeError\n} from \"~/domain/file/errors.js\";\nimport { FileBeforeCreateEvent, FileAfterCreateEvent } from \"./events.js\";\nimport { FmPermissions } from \"~/features/shared/abstractions.js\";\nimport { IdentityContext } from \"@webiny/api-core/features/security/IdentityContext/index.js\";\nimport { Identity } from \"~/domain/identity/Identity.js\";\nimport { isValidFileKey } from \"~/features/file/shared/isValidFileKey.js\";\n\nclass CreateFileUseCaseImpl implements UseCaseAbstraction.Interface {\n constructor(\n private identityContext: IdentityContext.Interface,\n private permissions: FmPermissions.Interface,\n private repository: CreateFileRepository.Interface,\n private getSettings: GetSettingsUseCase.Interface,\n private eventPublisher: EventPublisher.Interface\n ) {}\n\n async execute(\n input: CreateFileInput,\n meta?: Record<string, any>\n ): Promise<Result<File, UseCaseAbstraction.Error>> {\n const hasPermission = await this.permissions.canCreate(\"file\");\n if (!hasPermission) {\n return Result.fail(new FileNotAuthorizedError());\n }\n\n const validationResult = await this.validateInput(input);\n if (validationResult.isFail()) {\n return Result.fail(validationResult.error);\n }\n\n const [id] = input.key.split(\"/\");\n const fileId = input.id || id;\n\n // Security: the key must point at this file's own upload. Imports and migrations\n // (running without authorization) may register any key.\n if (this.identityContext.isAuthorizationEnabled() && !isValidFileKey(fileId, input.key)) {\n return Result.fail(new InvalidFileKeyError({ id: fileId, key: input.key }));\n }\n\n const currentIdentity = this.identityContext.getIdentity();\n\n // Attribution and dates come from the server. Only full access, or code running without\n // authorization (imports, migrations), may set them.\n const systemInput: Partial<CreateFileInput> =\n !this.identityContext.isAuthorizationEnabled() ||\n (await this.identityContext.hasFullAccess())\n ? input\n : {};\n\n // Prepare file input\n const fileInput: FileInput = {\n id: fileId,\n key: input.key,\n name: input.name,\n size: input.size,\n type: input.type,\n metadata: input.metadata || {},\n location: input.location || { folderId: \"root\" },\n tags: input.tags || [],\n description: input.description ?? \"\",\n extensions: meta || {},\n // system attributes\n createdOn: systemInput.createdOn,\n modifiedOn: systemInput.modifiedOn,\n savedOn: systemInput.savedOn,\n createdBy: systemInput.createdBy\n ? Identity.from(systemInput.createdBy)\n : Identity.from(currentIdentity),\n modifiedBy: systemInput.modifiedBy ? Identity.from(systemInput.modifiedBy) : undefined,\n savedBy: systemInput.savedBy\n ? Identity.from(systemInput.savedBy)\n : Identity.from(currentIdentity)\n };\n\n await this.eventPublisher.publish(new FileBeforeCreateEvent({ file: fileInput, meta }));\n\n const result = await this.repository.execute(fileInput);\n\n if (result.isFail()) {\n return Result.fail(result.error);\n }\n\n await this.eventPublisher.publish(new FileAfterCreateEvent({ file: result.value, meta }));\n\n return Result.ok(result.value);\n }\n\n private async validateInput(\n input: CreateFileInput\n ): Promise<Result<void, InvalidFileSizeError>> {\n const settingsResult = await this.getSettings.execute();\n\n if (settingsResult.isFail()) {\n return Result.ok();\n }\n\n const settings = settingsResult.value;\n\n if (settings) {\n // Validate file size\n if (\n input.size < settings.uploadMinFileSize ||\n input.size > settings.uploadMaxFileSize\n ) {\n return Result.fail(\n new InvalidFileSizeError({\n size: input.size,\n minSize: settings.uploadMinFileSize,\n maxSize: settings.uploadMaxFileSize\n })\n );\n }\n }\n\n return Result.ok();\n }\n}\n\nexport const CreateFileUseCase = UseCaseAbstraction.createImplementation({\n implementation: CreateFileUseCaseImpl,\n dependencies: [\n IdentityContext,\n FmPermissions,\n CreateFileRepository,\n GetSettingsUseCase,\n EventPublisher\n ]\n});\n"],"names":["CreateFileUseCaseImpl","identityContext","permissions","repository","getSettings","eventPublisher","input","meta","hasPermission","Result","FileNotAuthorizedError","validationResult","id","fileId","isValidFileKey","InvalidFileKeyError","currentIdentity","systemInput","fileInput","Identity","undefined","FileBeforeCreateEvent","result","FileAfterCreateEvent","settingsResult","settings","InvalidFileSizeError","CreateFileUseCase","UseCaseAbstraction","IdentityContext","FmPermissions","CreateFileRepository","GetSettingsUseCase","EventPublisher"],"mappings":";;;;;;;;;;AAoBA,MAAMA;IACF,YACYC,eAA0C,EAC1CC,WAAoC,EACpCC,U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6B;QACAC;QACAC;QACAC;QACAC;KACH;AACL"}
@@ -1,6 +1,6 @@
1
1
  import type { Result } from "@webiny/feature/api";
2
2
  import type { CreatedBy, File, FileInput } from "../../../domain/file/types.js";
3
- import { type FilePersistenceError, type InvalidFileSizeError, type FileAlreadyExistsError, FileNotAuthorizedError } from "../../../domain/file/errors.js";
3
+ import { type FilePersistenceError, type InvalidFileSizeError, type FileAlreadyExistsError, type InvalidFileKeyError, FileNotAuthorizedError } from "../../../domain/file/errors.js";
4
4
  export interface CreateFileInput {
5
5
  id?: string;
6
6
  key: string;
@@ -30,6 +30,7 @@ export interface ICreateFileRepository {
30
30
  export interface ICreateFileRepositoryErrors {
31
31
  notAuthorized: FileNotAuthorizedError;
32
32
  persistence: FilePersistenceError;
33
+ alreadyExists: FileAlreadyExistsError;
33
34
  }
34
35
  type RepositoryError = ICreateFileRepositoryErrors[keyof ICreateFileRepositoryErrors];
35
36
  /** Persist a newly created file. */
@@ -48,6 +49,7 @@ export interface ICreateFileUseCaseErrors {
48
49
  notAuthorized: FileNotAuthorizedError;
49
50
  persistence: FilePersistenceError;
50
51
  invalidSize: InvalidFileSizeError;
52
+ invalidKey: InvalidFileKeyError;
51
53
  alreadyExists: FileAlreadyExistsError;
52
54
  }
53
55
  type UseCaseError = ICreateFileUseCaseErrors[keyof ICreateFileUseCaseErrors];
@@ -1 +1 @@
1
- {"version":3,"file":"features/file/CreateFile/abstractions.js","sources":["../../../../src/features/file/CreateFile/abstractions.ts"],"sourcesContent":["import { createAbstraction } from \"@webiny/feature/api\";\nimport type { Result } from \"@webiny/feature/api\";\nimport type { CreatedBy, File, FileInput } from \"~/domain/file/types.js\";\nimport {\n type FilePersistenceError,\n type InvalidFileSizeError,\n type FileAlreadyExistsError,\n FileNotAuthorizedError\n} from \"~/domain/file/errors.js\";\n\nexport interface CreateFileInput {\n id?: string;\n key: string;\n size: number;\n type: string;\n name: string;\n metadata?: Record<string, any>;\n extensions?: Record<string, any>;\n tags?: string[];\n description?: string;\n location?: { folderId: string };\n // System attributes\n createdOn?: string;\n createdBy?: CreatedBy;\n modifiedOn?: string;\n modifiedBy?: CreatedBy;\n savedOn?: string;\n savedBy?: CreatedBy;\n}\n\n/**\n * CreateFile repository interface\n */\nexport interface ICreateFileRepository {\n execute(data: FileInput): Promise<Result<File, RepositoryError>>;\n}\n\nexport interface ICreateFileRepositoryErrors {\n notAuthorized: FileNotAuthorizedError;\n persistence: FilePersistenceError;\n}\n\ntype RepositoryError = ICreateFileRepositoryErrors[keyof ICreateFileRepositoryErrors];\n\n/** Persist a newly created file. */\nexport const CreateFileRepository =\n createAbstraction<ICreateFileRepository>(\"CreateFileRepository\");\n\nexport namespace CreateFileRepository {\n export type Interface = ICreateFileRepository;\n export type Error = RepositoryError;\n}\n\n/**\n * CreateFile use case interface\n */\nexport interface ICreateFileUseCase {\n execute(\n input: CreateFileInput,\n meta?: Record<string, any>\n ): Promise<Result<File, UseCaseError>>;\n}\n\nexport interface ICreateFileUseCaseErrors {\n notAuthorized: FileNotAuthorizedError;\n persistence: FilePersistenceError;\n invalidSize: InvalidFileSizeError;\n alreadyExists: FileAlreadyExistsError;\n}\n\ntype UseCaseError = ICreateFileUseCaseErrors[keyof ICreateFileUseCaseErrors];\n\n/** Upload and create a new file. */\nexport const CreateFileUseCase = createAbstraction<ICreateFileUseCase>(\"CreateFileUseCase\");\n\nexport namespace CreateFileUseCase {\n export type Interface = ICreateFileUseCase;\n export type Error = UseCaseError;\n}\n"],"names":["CreateFileRepository","createAbstraction","CreateFileUseCase"],"mappings":";AA6CO,MAAMA,uBACTC,kBAAyC;AA2BtC,MAAMC,oBAAoBD,kBAAsC"}
1
+ {"version":3,"file":"features/file/CreateFile/abstractions.js","sources":["../../../../src/features/file/CreateFile/abstractions.ts"],"sourcesContent":["import { createAbstraction } from \"@webiny/feature/api\";\nimport type { Result } from \"@webiny/feature/api\";\nimport type { CreatedBy, File, FileInput } from \"~/domain/file/types.js\";\nimport {\n type FilePersistenceError,\n type InvalidFileSizeError,\n type FileAlreadyExistsError,\n type InvalidFileKeyError,\n FileNotAuthorizedError\n} from \"~/domain/file/errors.js\";\n\nexport interface CreateFileInput {\n id?: string;\n key: string;\n size: number;\n type: string;\n name: string;\n metadata?: Record<string, any>;\n extensions?: Record<string, any>;\n tags?: string[];\n description?: string;\n location?: { folderId: string };\n // System attributes\n createdOn?: string;\n createdBy?: CreatedBy;\n modifiedOn?: string;\n modifiedBy?: CreatedBy;\n savedOn?: string;\n savedBy?: CreatedBy;\n}\n\n/**\n * CreateFile repository interface\n */\nexport interface ICreateFileRepository {\n execute(data: FileInput): Promise<Result<File, RepositoryError>>;\n}\n\nexport interface ICreateFileRepositoryErrors {\n notAuthorized: FileNotAuthorizedError;\n persistence: FilePersistenceError;\n alreadyExists: FileAlreadyExistsError;\n}\n\ntype RepositoryError = ICreateFileRepositoryErrors[keyof ICreateFileRepositoryErrors];\n\n/** Persist a newly created file. */\nexport const CreateFileRepository =\n createAbstraction<ICreateFileRepository>(\"CreateFileRepository\");\n\nexport namespace CreateFileRepository {\n export type Interface = ICreateFileRepository;\n export type Error = RepositoryError;\n}\n\n/**\n * CreateFile use case interface\n */\nexport interface ICreateFileUseCase {\n execute(\n input: CreateFileInput,\n meta?: Record<string, any>\n ): Promise<Result<File, UseCaseError>>;\n}\n\nexport interface ICreateFileUseCaseErrors {\n notAuthorized: FileNotAuthorizedError;\n persistence: FilePersistenceError;\n invalidSize: InvalidFileSizeError;\n invalidKey: InvalidFileKeyError;\n alreadyExists: FileAlreadyExistsError;\n}\n\ntype UseCaseError = ICreateFileUseCaseErrors[keyof ICreateFileUseCaseErrors];\n\n/** Upload and create a new file. */\nexport const CreateFileUseCase = createAbstraction<ICreateFileUseCase>(\"CreateFileUseCase\");\n\nexport namespace CreateFileUseCase {\n export type Interface = ICreateFileUseCase;\n export type Error = UseCaseError;\n}\n"],"names":["CreateFileRepository","createAbstraction","CreateFileUseCase"],"mappings":";AA+CO,MAAMA,uBACTC,kBAAyC;AA4BtC,MAAMC,oBAAoBD,kBAAsC"}
@@ -4,12 +4,14 @@ import { GetSettingsUseCase } from "../../settings/GetSettings/abstractions.js";
4
4
  import { EventPublisher } from "@webiny/api-core/features/eventPublisher/index.js";
5
5
  import type { File } from "../../../domain/file/types.js";
6
6
  import { FmPermissions } from "../../../features/shared/abstractions.js";
7
+ import { IdentityContext } from "@webiny/api-core/features/security/IdentityContext/index.js";
7
8
  declare class CreateFilesInBatchUseCaseImpl implements UseCaseAbstraction.Interface {
9
+ private identityContext;
8
10
  private permissions;
9
11
  private repository;
10
12
  private getSettings;
11
13
  private eventPublisher;
12
- constructor(permissions: FmPermissions.Interface, repository: CreateFilesInBatchRepository.Interface, getSettings: GetSettingsUseCase.Interface, eventPublisher: EventPublisher.Interface);
14
+ constructor(identityContext: IdentityContext.Interface, permissions: FmPermissions.Interface, repository: CreateFilesInBatchRepository.Interface, getSettings: GetSettingsUseCase.Interface, eventPublisher: EventPublisher.Interface);
13
15
  execute(input: CreateFilesInBatchInput): Promise<Result<File[], UseCaseAbstraction.Error>>;
14
16
  private validateInput;
15
17
  }
@@ -2,11 +2,14 @@ import { Result } from "@webiny/feature/api";
2
2
  import { CreateFilesInBatchRepository, CreateFilesInBatchUseCase } from "./abstractions.js";
3
3
  import { GetSettingsUseCase } from "../../settings/GetSettings/abstractions.js";
4
4
  import { EventPublisher } from "@webiny/api-core/features/eventPublisher/index.js";
5
- import { FileNotAuthorizedError, InvalidFileSizeError } from "../../../domain/file/errors.js";
5
+ import { FileNotAuthorizedError, InvalidFileKeyError, InvalidFileSizeError } from "../../../domain/file/errors.js";
6
6
  import { FileAfterBatchCreateEvent, FileBeforeBatchCreateEvent } from "./events.js";
7
7
  import { FmPermissions } from "../../shared/abstractions.js";
8
+ import { IdentityContext } from "@webiny/api-core/features/security/IdentityContext/index.js";
9
+ import { isValidFileKey } from "../shared/isValidFileKey.js";
8
10
  class CreateFilesInBatchUseCaseImpl {
9
- constructor(permissions, repository, getSettings, eventPublisher){
11
+ constructor(identityContext, permissions, repository, getSettings, eventPublisher){
12
+ this.identityContext = identityContext;
10
13
  this.permissions = permissions;
11
14
  this.repository = repository;
12
15
  this.getSettings = getSettings;
@@ -17,6 +20,13 @@ class CreateFilesInBatchUseCaseImpl {
17
20
  if (!hasPermission) return Result.fail(new FileNotAuthorizedError());
18
21
  const validationResult = await this.validateInput(input.files);
19
22
  if (validationResult.isFail()) return Result.fail(validationResult.error);
23
+ if (this.identityContext.isAuthorizationEnabled()) for (const file of input.files){
24
+ const fileId = file.id || file.key.split("/")[0];
25
+ if (!isValidFileKey(fileId, file.key)) return Result.fail(new InvalidFileKeyError({
26
+ id: fileId,
27
+ key: file.key
28
+ }));
29
+ }
20
30
  const fileInputs = input.files.map((file)=>{
21
31
  const [id] = file.key.split("/");
22
32
  return {
@@ -62,6 +72,7 @@ class CreateFilesInBatchUseCaseImpl {
62
72
  const CreateFilesInBatchUseCase_CreateFilesInBatchUseCase = CreateFilesInBatchUseCase.createImplementation({
63
73
  implementation: CreateFilesInBatchUseCaseImpl,
64
74
  dependencies: [
75
+ IdentityContext,
65
76
  FmPermissions,
66
77
  CreateFilesInBatchRepository,
67
78
  GetSettingsUseCase,
@@ -1 +1 @@
1
- {"version":3,"file":"features/file/CreateFilesInBatch/CreateFilesInBatchUseCase.js","sources":["../../../../src/features/file/CreateFilesInBatch/CreateFilesInBatchUseCase.ts"],"sourcesContent":["import { Result } from \"@webiny/feature/api\";\nimport {\n CreateFilesInBatchUseCase as UseCaseAbstraction,\n CreateFilesInBatchInput,\n CreateFilesInBatchRepository\n} from \"./abstractions.js\";\nimport { GetSettingsUseCase } from \"../../settings/GetSettings/abstractions.js\";\nimport { EventPublisher } from \"@webiny/api-core/features/eventPublisher/index.js\";\nimport type { File, FileInput } from \"~/domain/file/types.js\";\nimport { FileNotAuthorizedError, InvalidFileSizeError } from \"~/domain/file/errors.js\";\nimport { FileBeforeBatchCreateEvent, FileAfterBatchCreateEvent } from \"./events.js\";\nimport { FmPermissions } from \"~/features/shared/abstractions.js\";\nimport { CreateFileInput } from \"~/features/file/CreateFile/abstractions.js\";\n\nclass CreateFilesInBatchUseCaseImpl implements UseCaseAbstraction.Interface {\n public constructor(\n private permissions: FmPermissions.Interface,\n private repository: CreateFilesInBatchRepository.Interface,\n private getSettings: GetSettingsUseCase.Interface,\n private eventPublisher: EventPublisher.Interface\n ) {}\n\n public async execute(\n input: CreateFilesInBatchInput\n ): Promise<Result<File[], UseCaseAbstraction.Error>> {\n const hasPermission = await this.permissions.canCreate(\"file\");\n if (!hasPermission) {\n return Result.fail(new FileNotAuthorizedError());\n }\n\n // Validate all files\n const validationResult = await this.validateInput(input.files);\n if (validationResult.isFail()) {\n return Result.fail(validationResult.error);\n }\n\n // Prepare file inputs with defaults\n const fileInputs: FileInput[] = input.files.map(file => {\n const [id] = file.key.split(\"/\");\n return {\n id: file.id || id,\n key: file.key,\n name: file.name,\n size: file.size,\n type: file.type,\n metadata: file.metadata || {},\n location: file.location || { folderId: \"root\" },\n tags: file.tags || [],\n extensions: input.meta || {}\n };\n });\n\n await this.eventPublisher.publish(\n new FileBeforeBatchCreateEvent({ files: fileInputs, meta: input.meta })\n );\n\n const result = await this.repository.createBatch(fileInputs);\n\n if (result.isFail()) {\n return Result.fail(result.error);\n }\n\n await this.eventPublisher.publish(\n new FileAfterBatchCreateEvent({ files: result.value, meta: input.meta })\n );\n\n return Result.ok(result.value);\n }\n\n private async validateInput(\n files: CreateFileInput[]\n ): Promise<Result<void, InvalidFileSizeError>> {\n const settingsResult = await this.getSettings.execute();\n\n if (settingsResult.isFail()) {\n return Result.ok();\n }\n\n const settings = settingsResult.value;\n\n if (settings) {\n for (const input of files) {\n // Validate file size\n if (\n input.size < settings.uploadMinFileSize ||\n input.size > settings.uploadMaxFileSize\n ) {\n return Result.fail(\n new InvalidFileSizeError({\n size: input.size,\n minSize: settings.uploadMinFileSize,\n maxSize: settings.uploadMaxFileSize\n })\n );\n }\n }\n }\n\n return Result.ok();\n }\n}\n\nexport const CreateFilesInBatchUseCase = UseCaseAbstraction.createImplementation({\n implementation: CreateFilesInBatchUseCaseImpl,\n dependencies: [FmPermissions, CreateFilesInBatchRepository, GetSettingsUseCase, EventPublisher]\n});\n"],"names":["CreateFilesInBatchUseCaseImpl","permissions","repository","getSettings","eventPublisher","input","hasPermission","Result","FileNotAuthorizedError","validationResult","fileInputs","file","id","FileBeforeBatchCreateEvent","result","FileAfterBatchCreateEvent","files","settingsResult","settings","InvalidFileSizeError","CreateFilesInBatchUseCase","UseCaseAbstraction","FmPermissions","CreateFilesInBatchRepository","GetSettingsUseCase","EventPublisher"],"mappings":";;;;;;;AAcA,MAAMA;IACF,YACYC,WAAoC,EACpCC,UAAkD,EAClDC,WAAyC,EACzCC,cAAwC,CAClD;aAJUH,WAAW,GAAXA;aACAC,UAAU,GAAVA;aACAC,WAAW,GAAXA;aACAC,cAAc,GAAdA;IACT;IAEH,MAAa,QACTC,KAA8B,EACmB;QACjD,MAAMC,gBAAgB,MAAM,IAAI,CAAC,WAAW,CAAC,SAAS,CAAC;QACvD,IAAI,CAACA,eACD,OAAOC,OAAO,IAAI,CAAC,IAAIC;QAI3B,MAAMC,mBAAmB,MAAM,IAAI,CAAC,aAAa,CAACJ,MAAM,KAAK;QAC7D,IAAII,iBAAiB,MAAM,IACvB,OAAOF,OAAO,IAAI,CAACE,iBAAiB,KAAK;QAI7C,MAAMC,aAA0BL,MAAM,KAAK,CAAC,GAAG,CAACM,CAAAA;YAC5C,MAAM,CAACC,GAAG,GAAGD,KAAK,GAAG,CAAC,KAAK,CAAC;YAC5B,OAAO;gBACH,IAAIA,KAAK,EAAE,IAAIC;gBACf,KAAKD,KAAK,GAAG;gBACb,MAAMA,KAAK,IAAI;gBACf,MAAMA,KAAK,IAAI;gBACf,MAAMA,KAAK,IAAI;gBACf,UAAUA,KAAK,QAAQ,IAAI,CAAC;gBAC5B,UAAUA,KAAK,QAAQ,IAAI;oBAAE,UAAU;gBAAO;gBAC9C,MAAMA,KAAK,IAAI,IAAI,EAAE;gBACrB,YAAYN,MAAM,IAAI,IAAI,CAAC;YAC/B;QACJ;QAEA,MAAM,IAAI,CAAC,cAAc,CAAC,OAAO,CAC7B,IAAIQ,2BAA2B;YAAE,OAAOH;YAAY,MAAML,MAAM,IAAI;QAAC;QAGzE,MAAMS,SAAS,MAAM,IAAI,CAAC,UAAU,CAAC,WAAW,CAACJ;QAEjD,IAAII,OAAO,MAAM,IACb,OAAOP,OAAO,IAAI,CAACO,OAAO,KAAK;QAGnC,MAAM,IAAI,CAAC,cAAc,CAAC,OAAO,CAC7B,IAAIC,0BAA0B;YAAE,OAAOD,OAAO,KAAK;YAAE,MAAMT,MAAM,IAAI;QAAC;QAG1E,OAAOE,OAAO,EAAE,CAACO,OAAO,KAAK;IACjC;IAEA,MAAc,cACVE,KAAwB,EACmB;QAC3C,MAAMC,iBAAiB,MAAM,IAAI,CAAC,WAAW,CAAC,OAAO;QAErD,IAAIA,eAAe,MAAM,IACrB,OAAOV,OAAO,EAAE;QAGpB,MAAMW,WAAWD,eAAe,KAAK;QAErC,IAAIC,UACA;YAAA,KAAK,MAAMb,SAASW,MAEhB,IACIX,MAAM,IAAI,GAAGa,SAAS,iBAAiB,IACvCb,MAAM,IAAI,GAAGa,SAAS,iBAAiB,EAEvC,OAAOX,OAAO,IAAI,CACd,IAAIY,qBAAqB;gBACrB,MAAMd,MAAM,IAAI;gBAChB,SAASa,SAAS,iBAAiB;gBACnC,SAASA,SAAS,iBAAiB;YACvC;QAGZ;QAGJ,OAAOX,OAAO,EAAE;IACpB;AACJ;AAEO,MAAMa,sDAA4BC,0BAAAA,oBAAuC,CAAC;IAC7E,gBAAgBrB;IAChB,cAAc;QAACsB;QAAeC;QAA8BC;QAAoBC;KAAe;AACnG"}
1
+ {"version":3,"file":"features/file/CreateFilesInBatch/CreateFilesInBatchUseCase.js","sources":["../../../../src/features/file/CreateFilesInBatch/CreateFilesInBatchUseCase.ts"],"sourcesContent":["import { Result } from \"@webiny/feature/api\";\nimport {\n CreateFilesInBatchUseCase as UseCaseAbstraction,\n CreateFilesInBatchInput,\n CreateFilesInBatchRepository\n} from \"./abstractions.js\";\nimport { GetSettingsUseCase } from \"../../settings/GetSettings/abstractions.js\";\nimport { EventPublisher } from \"@webiny/api-core/features/eventPublisher/index.js\";\nimport type { File, FileInput } from \"~/domain/file/types.js\";\nimport {\n FileNotAuthorizedError,\n InvalidFileKeyError,\n InvalidFileSizeError\n} from \"~/domain/file/errors.js\";\nimport { FileBeforeBatchCreateEvent, FileAfterBatchCreateEvent } from \"./events.js\";\nimport { FmPermissions } from \"~/features/shared/abstractions.js\";\nimport { CreateFileInput } from \"~/features/file/CreateFile/abstractions.js\";\nimport { IdentityContext } from \"@webiny/api-core/features/security/IdentityContext/index.js\";\nimport { isValidFileKey } from \"~/features/file/shared/isValidFileKey.js\";\n\nclass CreateFilesInBatchUseCaseImpl implements UseCaseAbstraction.Interface {\n public constructor(\n private identityContext: IdentityContext.Interface,\n private permissions: FmPermissions.Interface,\n private repository: CreateFilesInBatchRepository.Interface,\n private getSettings: GetSettingsUseCase.Interface,\n private eventPublisher: EventPublisher.Interface\n ) {}\n\n public async execute(\n input: CreateFilesInBatchInput\n ): Promise<Result<File[], UseCaseAbstraction.Error>> {\n const hasPermission = await this.permissions.canCreate(\"file\");\n if (!hasPermission) {\n return Result.fail(new FileNotAuthorizedError());\n }\n\n // Validate all files\n const validationResult = await this.validateInput(input.files);\n if (validationResult.isFail()) {\n return Result.fail(validationResult.error);\n }\n\n // Security: each key must point at its own file's upload. Imports and migrations\n // (running without authorization) may register any key.\n if (this.identityContext.isAuthorizationEnabled()) {\n for (const file of input.files) {\n const fileId = file.id || file.key.split(\"/\")[0];\n if (!isValidFileKey(fileId, file.key)) {\n return Result.fail(new InvalidFileKeyError({ id: fileId, key: file.key }));\n }\n }\n }\n\n // Prepare file inputs with defaults\n const fileInputs: FileInput[] = input.files.map(file => {\n const [id] = file.key.split(\"/\");\n return {\n id: file.id || id,\n key: file.key,\n name: file.name,\n size: file.size,\n type: file.type,\n metadata: file.metadata || {},\n location: file.location || { folderId: \"root\" },\n tags: file.tags || [],\n extensions: input.meta || {}\n };\n });\n\n await this.eventPublisher.publish(\n new FileBeforeBatchCreateEvent({ files: fileInputs, meta: input.meta })\n );\n\n const result = await this.repository.createBatch(fileInputs);\n\n if (result.isFail()) {\n return Result.fail(result.error);\n }\n\n await this.eventPublisher.publish(\n new FileAfterBatchCreateEvent({ files: result.value, meta: input.meta })\n );\n\n return Result.ok(result.value);\n }\n\n private async validateInput(\n files: CreateFileInput[]\n ): Promise<Result<void, InvalidFileSizeError>> {\n const settingsResult = await this.getSettings.execute();\n\n if (settingsResult.isFail()) {\n return Result.ok();\n }\n\n const settings = settingsResult.value;\n\n if (settings) {\n for (const input of files) {\n // Validate file size\n if (\n input.size < settings.uploadMinFileSize ||\n input.size > settings.uploadMaxFileSize\n ) {\n return Result.fail(\n new InvalidFileSizeError({\n size: input.size,\n minSize: settings.uploadMinFileSize,\n maxSize: settings.uploadMaxFileSize\n })\n );\n }\n }\n }\n\n return Result.ok();\n }\n}\n\nexport const CreateFilesInBatchUseCase = UseCaseAbstraction.createImplementation({\n implementation: CreateFilesInBatchUseCaseImpl,\n dependencies: [\n IdentityContext,\n FmPermissions,\n CreateFilesInBatchRepository,\n GetSettingsUseCase,\n EventPublisher\n ]\n});\n"],"names":["CreateFilesInBatchUseCaseImpl","identityContext","permissions","repository","getSettings","eventPublisher","input","hasPermission","Result","FileNotAuthorizedError","validationResult","file","fileId","isValidFileKey","InvalidFileKeyError","fileInputs","id","FileBeforeBatchCreateEvent","result","FileAfterBatchCreateEvent","files","settingsResult","settings","InvalidFileSizeError","CreateFilesInBatchUseCase","UseCaseAbstraction","IdentityContext","FmPermissions","CreateFilesInBatchRepository","GetSettingsUseCase","EventPublisher"],"mappings":";;;;;;;;;AAoBA,MAAMA;IACF,YACYC,eAA0C,EAC1CC,WAAoC,EACpCC,UAAkD,EAClDC,WAAyC,EACzCC,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7B,IAAIW,2BAA2B;YAAE,OAAOF;YAAY,MAAMT,MAAM,IAAI;QAAC;QAGzE,MAAMY,SAAS,MAAM,IAAI,CAAC,UAAU,CAAC,WAAW,CAACH;QAEjD,IAAIG,OAAO,MAAM,IACb,OAAOV,OAAO,IAAI,CAACU,OAAO,KAAK;QAGnC,MAAM,IAAI,CAAC,cAAc,CAAC,OAAO,CAC7B,IAAIC,0BAA0B;YAAE,OAAOD,OAAO,KAAK;YAAE,MAAMZ,MAAM,IAAI;QAAC;QAG1E,OAAOE,OAAO,EAAE,CAACU,OAAO,KAAK;IACjC;IAEA,MAAc,cACVE,KAAwB,EACmB;QAC3C,MAAMC,iBAAiB,MAAM,IAAI,CAAC,WAAW,CAAC,OAAO;QAErD,IAAIA,eAAe,MAAM,IACrB,OAAOb,OAAO,EAAE;QAGpB,MAAMc,WAAWD,eAAe,KAAK;QAErC,IAAIC,UACA;YAAA,KAAK,MAAMhB,SAASc,MAEhB,IACId,MAAM,IAAI,GAAGgB,SAAS,iBAAiB,IACvChB,MAAM,IAAI,GAAGgB,SAAS,iBAAiB,EAEvC,OAAOd,OAAO,IAAI,CACd,IAAIe,qBAAqB;gBACrB,MAAMjB,MAAM,IAAI;gBAChB,SAASgB,SAAS,iBAAiB;gBACnC,SAASA,SAAS,iBAAiB;YACvC;QAGZ;QAGJ,OAAOd,OAAO,EAAE;IACpB;AACJ;AAEO,MAAMgB,sDAA4BC,0BAAAA,oBAAuC,CAAC;IAC7E,gBAAgBzB;IAChB,cAAc;QACV0B;QACAC;QACAC;QACAC;QACAC;KACH;AACL"}
@@ -1,6 +1,6 @@
1
1
  import type { Result } from "@webiny/feature/api";
2
2
  import type { File, FileInput } from "../../../domain/file/types.js";
3
- import { type FilePersistenceError, type InvalidFileSizeError, FileNotAuthorizedError } from "../../../domain/file/errors.js";
3
+ import { type FilePersistenceError, type InvalidFileSizeError, type InvalidFileKeyError, FileNotAuthorizedError } from "../../../domain/file/errors.js";
4
4
  export interface CreateFilesInBatchInput {
5
5
  files: FileInput[];
6
6
  meta?: Record<string, any>;
@@ -31,6 +31,7 @@ export interface ICreateFilesInBatchUseCaseErrors {
31
31
  notAuthorized: FileNotAuthorizedError;
32
32
  persistence: FilePersistenceError;
33
33
  invalidSize: InvalidFileSizeError;
34
+ invalidKey: InvalidFileKeyError;
34
35
  }
35
36
  type UseCaseError = ICreateFilesInBatchUseCaseErrors[keyof ICreateFilesInBatchUseCaseErrors];
36
37
  /** Upload and create multiple files in batch. */