Skip to content

Commit

Permalink
Extend file adapter with url sign util and add signature and expirati…
Browse files Browse the repository at this point in the history
…on check in gridfs webhook
  • Loading branch information
Mikearaya authored and pozylon committed Dec 13, 2024
1 parent 70ea03b commit bab4558
Show file tree
Hide file tree
Showing 5 changed files with 44 additions and 5 deletions.
2 changes: 1 addition & 1 deletion examples/kitchensink/boot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ const start = async () => {
],
options: {
files: {
privateFileSharingMaxAge: 1111111111,
privateFileSharingMaxAge: 86400000,
},
payment: {
filterSupportedProviders: async ({ providers }) => {
Expand Down
19 changes: 15 additions & 4 deletions packages/api/src/resolvers/type/media-types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { File as FileType } from '@unchainedshop/core-files';
import { filesSettings, File as FileType, getFileAdapter } from '@unchainedshop/core-files';
import { Context } from '../../context.js';
import { checkAction } from '../../acl.js';
import { actions } from '../../roles/index.js';
Expand All @@ -8,11 +8,22 @@ export interface MediaHelperTypes {
}

export const Media: MediaHelperTypes = {
url: async (root, params, context) => {
url: async (file, params, context) => {
const { modules } = context;
try {
await checkAction(context, actions.downloadFile, [root, params]);
return modules.files.getUrl(root, params);
await checkAction(context, actions.downloadFile, [file, params]);
const fileUploadAdapter = getFileAdapter();
const mediaUrl = modules.files.getUrl(file, params);
if (file.isPrivate) {
const expiryTimestamp = new Date(
new Date().getTime() + (filesSettings?.privateFileSharingMaxAge || 0),
).getTime();

const mediaSignature = fileUploadAdapter.signUrl(file?._id, expiryTimestamp);
return `${mediaUrl}?s=${mediaSignature}&e=${expiryTimestamp}`;
} else {
return mediaUrl;
}
} catch (e) {
console.error(e);
return null;
Expand Down
1 change: 1 addition & 0 deletions packages/core-files/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export type File = {
size?: number;
type?: string;
url?: string;
isPrivate?: boolean;
} & TimestampFields;

export type SignedFileUpload = File & {
Expand Down
13 changes: 13 additions & 0 deletions packages/file-upload/src/director/FileAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,20 @@ import { Readable } from 'stream';
import { log, LogLevel } from '@unchainedshop/logger';
import { IBaseAdapter } from '@unchainedshop/utils';
import { UploadedFile, UploadFileData } from '../types.js';
import crypto from 'crypto';

const signUrl = (fileUrl: string, expiry: number): string => {
const secretKey = process.env.UNCHAINED_SECRET;
if (!secretKey) {
throw new Error('UNCHAINED_SECRET is not set in environment variables');
}

const data = `${fileUrl}:${expiry}`;
return crypto.createHmac('sha256', secretKey).update(data).digest('hex');
};

export interface IFileAdapter<Context = unknown> extends IBaseAdapter {
signUrl: (fileUrl: string, expiry: number) => string;
createSignedURL: (
directoryName: string,
fileName: string,
Expand All @@ -29,6 +41,7 @@ export interface IFileAdapter<Context = unknown> extends IBaseAdapter {
createDownloadStream: (file: UploadedFile, unchainedAPI: Context) => Promise<Readable>;
}
export const FileAdapter: Omit<IFileAdapter, 'key' | 'label' | 'version'> = {
signUrl,
createSignedURL() {
return new Promise<null>((resolve) => {
resolve(null);
Expand Down
14 changes: 14 additions & 0 deletions packages/plugins/src/files/gridfs/gridfs-webhook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import express from 'express';
import sign from './sign.js';
import { configureGridFSFileUploadModule } from './index.js';
import { Context } from '@unchainedshop/api';
import { getFileAdapter } from '@unchainedshop/core-files';

const { ROOT_URL } = process.env;

Expand Down Expand Up @@ -76,8 +77,21 @@ export const gridfsHandler = async (

if (req.method === 'GET') {
const fileId = fileName;
const { s: signature, e: expiryTimestamp } = req.query;

const file = await modules.gridfsFileUploads.getFileInfo(directoryName, fileId);
if (signature && expiryTimestamp) {
const fileDocument = await modules.files.findFile({ fileId });
if (fileDocument.isPrivate) {
const fileAdapter = getFileAdapter();
const fileSignature = fileAdapter.signUrl(fileId, parseInt(expiryTimestamp));
if (fileSignature !== signature || parseInt(expiryTimestamp, 10) <= Date.now()) {
res.statusCode = 403;
res.end('Access restricted: Invalid or expired signature.');
return;
}
}
}
if (file?.metadata?.['content-type']) {
res.setHeader('Content-Type', file.metadata['content-type']);
}
Expand Down

0 comments on commit bab4558

Please sign in to comment.