Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 80 additions & 2 deletions custom/uploader.vue
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,8 @@ const progress = ref(0);
const uploaded = ref(false);
const uploadedSize = ref(0);

const downloadFileUrl = ref('');

watch(() => uploaded, (value) => {
Copy link

Copilot AI Nov 24, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The watch function is incorrectly watching the entire uploaded ref object instead of its value. It should be watch(uploaded, (value) => ...) or watch(() => uploaded.value, (value) => ...) to properly react to changes in the uploaded state.

Suggested change
watch(() => uploaded, (value) => {
watch(uploaded, (value) => {

Copilot uses AI. Check for mistakes.
emit('update:emptiness', !value);
});
Expand All @@ -118,9 +120,45 @@ function uploadGeneratedImage(imgBlob) {
});
}

onMounted(() => {
onMounted(async () => {
const previewColumnName = `previewUrl_${props.meta.pluginInstanceId}`;
if (props.record[previewColumnName]) {

let queryValues;
try {
queryValues = JSON.parse(atob(route.query.values as string));
} catch (e) {
queryValues = {};
}

if (queryValues[props.meta.pathColumnName]) {


Comment on lines +134 to +135
Copy link

Copilot AI Nov 24, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Empty lines (134-135) should be removed to maintain consistent code formatting.

Suggested change

Copilot uses AI. Check for mistakes.
downloadFileUrl.value = queryValues[props.meta.pathColumnName];

const resp = await callAdminForthApi({
path: `/plugin/${props.meta.pluginInstanceId}/get-file-download-url`,
method: 'POST',
body: {
filePath: queryValues[props.meta.pathColumnName]
},
});
if (resp.error) {
adminforth.alert({
message: t('Error getting file url'),
variant: 'danger'
});
return;
}
const file = await downloadAsFile(resp.url);
if (!file) {
return;
}
onFileChange({
target: {
files: [file],
},
});
} else if (props.record[previewColumnName]) {
imgPreview.value = props.record[previewColumnName];
uploaded.value = true;
emit('update:emptiness', false);
Expand Down Expand Up @@ -300,6 +338,46 @@ const onFileChange = async (e) => {
}
}

async function downloadAsFile(url) {
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ fileDownloadURL: url }),
};
const fullPath = `${import.meta.env.VITE_ADMINFORTH_PUBLIC_PATH || ''}/adminapi/v1/plugin/${props.meta.pluginInstanceId}/proxy-download`;
const resp = await fetch(fullPath, options);
let isError = false;
try {
const jsonResp = await resp.clone().json();
if (jsonResp.error) {
adminforth.alert({
message: t('Error uploading file'),
variant: 'danger'
});
isError = true;
}
} catch (e) {

}

if (isError) {
return null;
}

const blob = await resp.blob();

const filename = url.split('/').pop()?.split('?')[0] || `file`;
const filenameParts = filename.split('.');
const extension = filenameParts.length > 1 ? filenameParts.pop() : '';
const nameWithoutExt = filenameParts.join('.');
const newFileName = extension
? `${nameWithoutExt}_copy_${Date.now()}.${extension}`
: `${filename}_copy_${Date.now()}`;

const file = new File([blob], newFileName, { type: blob.type });
return file;
}

</script>
50 changes: 50 additions & 0 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ export default class UploadPlugin extends AdminForthPlugin {
minShowWidth: this.options.preview?.minShowWidth,
generationPrompt: this.options.generation?.generationPrompt,
recorPkFieldName: this.resourceConfig.columns.find((column: any) => column.primaryKey)?.name,
pathColumnName: this.options.pathColumnName,
};
// define components which will be imported from other components
this.componentPath('imageGenerator.vue');
Expand Down Expand Up @@ -411,6 +412,55 @@ export default class UploadPlugin extends AdminForthPlugin {
},
});

server.endpoint({
method: 'POST',
path: `/plugin/${this.pluginInstanceId}/get-file-download-url`,
handler: async ({ body, adminUser }) => {
const { filePath } = body;
if (!filePath) {
return { error: 'Missing filePath' };
}
const url = await this.options.storageAdapter.getDownloadUrl(filePath, 1800);

return {
url,
};
},
Comment on lines +418 to +428
Copy link

Copilot AI Nov 24, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The endpoint doesn't validate user authorization to access the specific file. Any authenticated admin user can request a download URL for any file path. Consider adding authorization checks to ensure the user has permission to access the file, or at least verify the file belongs to a resource the user can access.

Copilot uses AI. Check for mistakes.
});

server.endpoint({
method: 'POST',
path: `/plugin/${this.pluginInstanceId}/proxy-download`,
handler: async ({ body, response }) => {
const { fileDownloadURL } = body;

if (!fileDownloadURL) {
return { error: 'Missing fileDownloadURL' };
}

if (!fileDownloadURL.startsWith(`http://${(this.options.storageAdapter as any).options.bucket}`) && !fileDownloadURL.startsWith(`https://${(this.options.storageAdapter as any).options.bucket}`)) {
return { error: 'Invalid fileDownloadURL ' };
Copy link

Copilot AI Nov 24, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The error message 'Invalid fileDownloadURL ' has a trailing space and doesn't provide helpful information about why the URL is invalid or what format is expected. Consider improving it to something like: 'Invalid fileDownloadURL: URL must be from the configured storage bucket'.

Suggested change
return { error: 'Invalid fileDownloadURL ' };
return { error: 'Invalid fileDownloadURL: URL must be from the configured storage bucket.' };

Copilot uses AI. Check for mistakes.
}

Comment on lines +441 to +444
Copy link

Copilot AI Nov 24, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The URL validation logic is insufficient and potentially vulnerable. It only checks if the URL starts with the bucket name but doesn't validate that the URL actually points to the storage adapter's domain. An attacker could craft a URL like http://bucket-name.malicious.com or https://bucket-name.evil.com that would bypass this check. Consider implementing proper URL parsing and validation that checks the full hostname against an allowlist.

Suggested change
if (!fileDownloadURL.startsWith(`http://${(this.options.storageAdapter as any).options.bucket}`) && !fileDownloadURL.startsWith(`https://${(this.options.storageAdapter as any).options.bucket}`)) {
return { error: 'Invalid fileDownloadURL ' };
}
let allowedHostnames: string[] = [];
// Attempt to build an allowlist of valid hostnames for the storage adapter
const storageOptions = (this.options.storageAdapter as any).options;
if (storageOptions.bucket && storageOptions.endpoint) {
// e.g., endpoint: "s3.amazonaws.com", bucket: "my-bucket"
// Allow both "my-bucket.s3.amazonaws.com" and "s3.amazonaws.com"
try {
const endpointUrl = new URL(storageOptions.endpoint.startsWith('http') ? storageOptions.endpoint : `https://${storageOptions.endpoint}`);
allowedHostnames.push(`${storageOptions.bucket}.${endpointUrl.hostname}`);
allowedHostnames.push(endpointUrl.hostname);
} catch (e) {
// fallback: just use bucket as hostname
allowedHostnames.push(storageOptions.bucket);
}
} else if (storageOptions.bucket) {
allowedHostnames.push(storageOptions.bucket);
}
let parsedUrl: URL;
try {
parsedUrl = new URL(fileDownloadURL);
} catch (e) {
return { error: 'Invalid fileDownloadURL (malformed URL)' };
}
if (!allowedHostnames.includes(parsedUrl.hostname)) {
return { error: 'Invalid fileDownloadURL (hostname not allowed)' };
}

Copilot uses AI. Check for mistakes.
const upstream = await fetch(fileDownloadURL);
if (!upstream.ok || !upstream.body) {
return { error: `Failed to download file (status ${upstream.status})` };
}

const contentType = upstream.headers.get('content-type') || 'application/octet-stream';
const contentLength = upstream.headers.get('content-length');
const contentDisposition = upstream.headers.get('content-disposition');

response.setHeader('Content-Type', contentType);
if (contentLength) response.setHeader('Content-Length', contentLength);
if (contentDisposition) response.setHeader('Content-Disposition', contentDisposition);

//@ts-ignore Node 18+: convert Web stream to Node stream and pipe to response
Readable.fromWeb(upstream.body).pipe(response.blobStream());
return null;
},
});
Comment on lines +434 to +462
Copy link

Copilot AI Nov 24, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The proxy-download endpoint doesn't validate user authorization. Any authenticated admin user can proxy download files from URLs that pass the bucket validation check. Consider adding authorization checks to ensure the user has permission to access the file being proxied.

Copilot uses AI. Check for mistakes.

}

}
Loading