Skip to content

πŸ“¨ The ultimate agentic social media scheduling tool πŸ€–

feat: update openai

Nevo Davidd3be71678927
diff --git a/apps/backend/src/api/routes/media.controller.ts b/apps/backend/src/api/routes/media.controller.ts
index ba6cc44e2..6d5b557a1 100644
--- a/apps/backend/src/api/routes/media.controller.ts
+++ b/apps/backend/src/api/routes/media.controller.ts
@@ -63,7 +63,7 @@ export class MediaController {
return {
output:
- (isPicturePrompt ? '' : 'data:image/png;base64,') +
+ 'data:image/png;base64,' +
(await this._mediaService.generateImage(prompt, org, isPicturePrompt)),
};
}
diff --git a/apps/frontend/src/components/launches/ai.image.tsx b/apps/frontend/src/components/launches/ai.image.tsx
index ed294b7b6..719174bbe 100644
--- a/apps/frontend/src/components/launches/ai.image.tsx
+++ b/apps/frontend/src/components/launches/ai.image.tsx
@@ -5,6 +5,8 @@ import Loading from '@gitroom/frontend/components/layout/loading';
import { useFetch } from '@gitroom/helpers/utils/custom.fetch';
import { useT } from '@gitroom/react/translation/get.transation.service.client';
import { useLaunchStore } from '@gitroom/frontend/components/new-launch/store';
+import { useModals } from '@gitroom/frontend/components/layout/new-modal';
+import { useToaster } from '@gitroom/react/toaster/toaster';
const list = [
'Realistic',
'Cartoon',
@@ -21,55 +23,131 @@ const list = [
'Pop Art',
'Fantasy Realism',
];
-export const AiImage: FC<{
- value: string;
+
+const AiImageModal: FC<{
+ close: () => void;
+ setLoading: (loading: boolean) => void;
onChange: (params: { id: string; path: string }) => void;
}> = (props) => {
+ const { close, setLoading, onChange } = props;
const t = useT();
- const { value, onChange } = props;
- const [loading, setLoading] = useState(false);
- const setLocked = useLaunchStore((p) => p.setLocked);
const fetch = useFetch();
- const generateImage = useCallback(
- (type: string) => async () => {
- setLoading(true);
- setLocked(true);
+ const toaster = useToaster();
+ const setLocked = useLaunchStore((p) => p.setLocked);
+ const [prompt, setPrompt] = useState('');
+ const [style, setStyle] = useState(list[0]);
+
+ const generate = useCallback(async () => {
+ if (!prompt.trim()) {
+ toaster.show(
+ t('please_type_your_prompt', 'Please type your prompt'),
+ 'warning'
+ );
+ return;
+ }
+
+ setLoading(true);
+ close();
+ setLocked(true);
+ try {
const image = await (
await fetch('/media/generate-image-with-prompt', {
method: 'POST',
body: JSON.stringify({
prompt: `
<!-- description -->
-${value}
+${prompt}
<!-- /description -->
<!-- style -->
-${type}
+${style}
<!-- /style -->
-
+
`,
}),
})
).json();
- setLoading(false);
- setLocked(false);
- onChange(image);
- },
- [value, onChange]
+ if (image) {
+ onChange(image);
+ }
+ } catch (e) {}
+ setLocked(false);
+ setLoading(false);
+ }, [prompt, style, onChange]);
+
+ return (
+ <div className="flex flex-col gap-[16px]">
+ <div className="flex flex-col gap-[6px]">
+ <div className="text-[14px]">{t('prompt', 'Prompt')}</div>
+ <textarea
+ value={prompt}
+ onChange={(e) => setPrompt(e.target.value)}
+ placeholder={t(
+ 'describe_the_image_you_want_to_generate',
+ 'Describe the image you want to generate'
+ )}
+ className="bg-input min-h-[150px] p-[16px] outline-none border-fifth border rounded-[4px] text-inputText placeholder-inputText"
+ />
+ </div>
+ <div className="flex flex-col gap-[6px]">
+ <div className="text-[14px]">{t('style', 'Style')}</div>
+ <div className="flex flex-wrap gap-[8px]">
+ {list.map((p) => (
+ <div
+ key={p}
+ onClick={() => setStyle(p)}
+ className={clsx(
+ 'cursor-pointer rounded-[4px] px-[10px] h-[30px] flex items-center text-[12px] border',
+ style === p
+ ? 'bg-[#612BD3] border-[#612BD3] text-white'
+ : 'bg-newColColor border-newBgLineColor'
+ )}
+ >
+ {p}
+ </div>
+ ))}
+ </div>
+ </div>
+ <div className="flex">
+ <Button type="button" onClick={generate} className="flex-1">
+ {t('generate', 'Generate')}
+ </Button>
+ </div>
+ </div>
);
+};
+
+export const AiImage: FC<{
+ value: string;
+ onChange: (params: { id: string; path: string }) => void;
+}> = (props) => {
+ const t = useT();
+ const { onChange } = props;
+ const [loading, setLoading] = useState(false);
+ const modals = useModals();
+
+ const openImageModal = useCallback(() => {
+ if (loading) {
+ return;
+ }
+ modals.openModal({
+ title: t('generate_ai_image', 'Generate AI Image'),
+ children: (close) => (
+ <AiImageModal
+ close={close}
+ setLoading={setLoading}
+ onChange={onChange}
+ />
+ ),
+ });
+ }, [loading, onChange]);
+
return (
- <div className="relative group">
+ <div className="relative">
<div
- {...(value.length < 30
- ? {
- 'data-tooltip-id': 'tooltip',
- 'data-tooltip-content':
- 'Please add at least 30 characters to generate AI image',
- }
- : {})}
+ onClick={openImageModal}
className={clsx(
- 'cursor-pointer h-[30px] rounded-[6px] justify-center items-center flex bg-newColColor px-[8px]',
- value.length < 30 && 'opacity-50'
+ 'cursor-pointer h-[30px] rounded-[6px] justify-center items-center flex bg-newColColor px-[8px]'
)}
>
{loading && (
@@ -107,20 +185,11 @@ ${type}
</defs>
</svg>
</div>
- <div className="text-[10px] font-[600] iconBreak:hidden block">{t('ai', 'AI')} Image</div>
+ <div className="text-[10px] font-[600] iconBreak:hidden block">
+ {t('ai', 'AI')} Image
+ </div>
</div>
</div>
- {value.length >= 30 && !loading && (
- <div className="text-[12px] -mt-[10px] w-[200px] absolute bottom-[100%] z-[500] start-0 hidden group-hover:block">
- <ul className="cursor-pointer rounded-[4px] border border-dashed mt-[3px] p-[5px] border-newBgLineColor bg-newColColor">
- {list.map((p) => (
- <li onClick={generateImage(p)} key={p} className="hover:bg-sixth">
- {p}
- </li>
- ))}
- </ul>
- </div>
- )}
</div>
);
};
diff --git a/apps/frontend/src/components/launches/ai.video.tsx b/apps/frontend/src/components/launches/ai.video.tsx
index 84ac317d1..7a8c93fca 100644
--- a/apps/frontend/src/components/launches/ai.video.tsx
+++ b/apps/frontend/src/components/launches/ai.video.tsx
@@ -6,7 +6,6 @@ import { useFetch } from '@gitroom/helpers/utils/custom.fetch';
import { useT } from '@gitroom/react/translation/get.transation.service.client';
import { useLaunchStore } from '@gitroom/frontend/components/new-launch/store';
import useSWR from 'swr';
-import { TopTitle } from '@gitroom/frontend/components/launches/helpers/top.title.component';
import { VideoWrapper } from '@gitroom/frontend/components/videos/video.render.component';
import { FormProvider, useForm } from 'react-hook-form';
import { useUser } from '@gitroom/frontend/components/layout/user.context';
@@ -17,12 +16,11 @@ import { createPortal } from 'react-dom';
export const Modal: FC<{
close: () => void;
- value: string;
type: any;
setLoading: (loading: boolean) => void;
onChange: (params: { id: string; path: string }) => void;
}> = (props) => {
- const { type, value, onChange, close, setLoading } = props;
+ const { type, onChange, close, setLoading } = props;
const fetch = useFetch();
const setLocked = useLaunchStore((state) => state.setLocked);
const form = useForm();
@@ -37,7 +35,7 @@ export const Modal: FC<{
).json();
}, []);
- const { data, mutate } = useSWR('copilot-credits', loadCredits);
+ const { data } = useSWR('copilot-credits', loadCredits);
const generate = useCallback(async () => {
await fetch(`/media/generate-video/${type.identifier}/allowed`);
@@ -67,17 +65,19 @@ export const Modal: FC<{
setLocked(false);
setLoading(false);
- }, [type, value, position]);
+ }, [type, position]);
return (
- <VideoContextWrapper.Provider value={{ value: value }}>
+ // Start with an empty prompt β€” we no longer copy the post's text field.
+ <VideoContextWrapper.Provider value={{ value: '' }}>
<form
onSubmit={form.handleSubmit(generate)}
className="flex flex-col gap-[10px]"
>
{createPortal(
<>{data?.credits || 0} credits left</>,
- document.querySelector('.top-title-content') || document.createElement('div')
+ document.querySelector('.top-title-content') ||
+ document.createElement('div')
)}
<FormProvider {...form}>
<div>
@@ -118,16 +118,51 @@ export const Modal: FC<{
);
};
+const AiVideoModal: FC<{
+ list: any[];
+ close: () => void;
+ setLoading: (loading: boolean) => void;
+ onChange: (params: { id: string; path: string }) => void;
+}> = (props) => {
+ const { list, close, setLoading, onChange } = props;
+ const t = useT();
+ const [type, setType] = useState<any | null>(
+ list.length === 1 ? list[0] : null
+ );
+
+ if (!type) {
+ return (
+ <div className="flex flex-col gap-[10px]">
+ <div className="text-[14px]">
+ {t('choose_a_video_type', 'Choose a video type')}
+ </div>
+ {list.map((p) => (
+ <Button key={p.identifier} type="button" onClick={() => setType(p)}>
+ {p.title}
+ </Button>
+ ))}
+ </div>
+ );
+ }
+
+ return (
+ <Modal
+ type={type}
+ close={close}
+ setLoading={setLoading}
+ onChange={onChange}
+ />
+ );
+};
+
export const AiVideo: FC<{
value: string;
onChange: (params: { id: string; path: string }) => void;
}> = (props) => {
const t = useT();
- const { value, onChange } = props;
+ const { onChange } = props;
const [loading, setLoading] = useState(false);
- const [type, setType] = useState<any | null>(null);
const fetch = useFetch();
- const { isTrailing } = useUser();
const modals = useModals();
const loadVideoList = useCallback(async () => {
@@ -145,104 +180,72 @@ export const AiVideo: FC<{
keepPreviousData: true,
});
- const generateVideo = useCallback(
- (type: { identifier: string }) => async () => {
- setType(type);
- modals.openModal({
- title: <div className="top-title-content" />,
- children: (close) => (
- <Modal
- onChange={onChange}
- setLoading={setLoading}
- close={() => {
- close();
- setType(null);
- }}
- type={type}
- value={value}
- />
- ),
- });
- },
- [value, onChange]
- );
+ const openVideoModal = useCallback(() => {
+ if (loading || !data?.length) {
+ return;
+ }
+ modals.openModal({
+ title: <div className="top-title-content" />,
+ children: (close) => (
+ <AiVideoModal
+ list={data}
+ onChange={onChange}
+ setLoading={setLoading}
+ close={close}
+ />
+ ),
+ });
+ }, [loading, data, onChange]);
if (isLoading || data?.length === 0) {
return null;
}
return (
- <>
- <div className="relative group">
+ <div className="relative">
+ <div
+ onClick={openVideoModal}
+ className={clsx(
+ 'cursor-pointer h-[30px] rounded-[6px] justify-center items-center flex bg-newColColor px-[8px]'
+ )}
+ >
+ {loading && (
+ <div className="absolute start-[50%] -translate-x-[50%]">
+ <Loading height={30} width={30} type="spin" color="#fff" />
+ </div>
+ )}
<div
- {...(value.length < 30
- ? {
- 'data-tooltip-id': 'tooltip',
- 'data-tooltip-content':
- 'Please add at least 30 characters to generate AI video',
- }
- : {})}
- className={clsx(
- 'cursor-pointer h-[30px] rounded-[6px] justify-center items-center flex bg-newColColor px-[8px]',
- value.length < 30 && 'opacity-50'
- )}
+ className={clsx('flex gap-[5px] items-center', loading && 'invisible')}
>
- {loading && (
- <div className="absolute start-[50%] -translate-x-[50%]">
- <Loading height={30} width={30} type="spin" color="#fff" />
- </div>
- )}
- <div
- className={clsx(
- 'flex gap-[5px] items-center',
- loading && 'invisible'
- )}
- >
- <div>
- <svg
- xmlns="http://www.w3.org/2000/svg"
- width="16"
- height="16"
- viewBox="0 0 16 16"
- fill="none"
- >
- <g clipPath="url(#clip0_2352_53058)">
- <path
- d="M8.06916 14.1663V2.04134M4.97208 14.1663V11.1351M4.97208 5.07259V2.04134M11.1662 14.1663V11.1351M9.09973 2.02152L4.8482 2.04134C3.80748 2.04134 3.28712 2.04134 2.88962 2.23957C2.53997 2.41394 2.25569 2.69218 2.07754 3.0344C1.875 3.42345 1.875 3.93275 1.875 4.95134L1.875 11.2563C1.875 12.2749 1.875 12.7842 2.07754 13.1733C2.25569 13.5155 2.53997 13.7937 2.88962 13.9681C3.28712 14.1663 3.80748 14.1663 4.8482 14.1663H11.2901C12.3308 14.1663 12.8512 14.1663 13.2487 13.9681C13.5984 13.7937 13.8826 13.5155 14.0608 13.1733C14.2633 12.7842 14.2633 12.2749 14.2633 11.2563V7.61426M1.875 5.07259L9.09973 5.06116M1.875 11.1351H14.2633M12.8141 1.20801L12.3949 2.02152C12.253 2.29684 12.1821 2.4345 12.0873 2.55379C12.0032 2.65965 11.9054 2.75455 11.7963 2.83614C11.6734 2.92809 11.5315 2.99692 11.2478 3.13458L10.4094 3.54134L11.2478 3.9481C11.5315 4.08576 11.6734 4.15459 11.7963 4.24654C11.9054 4.32814 12.0032 4.42303 12.0873 4.52889C12.1821 4.64818 12.253 4.78584 12.3949 5.06116L12.8141 5.87467L13.2333 5.06116C13.3751 4.78584 13.4461 4.64818 13.5408 4.52889C13.6249 4.42303 13.7227 4.32814 13.8318 4.24654C13.9548 4.15459 14.0966 4.08576 14.3804 3.9481L15.2188 3.54134L14.3804 3.13458C14.0966 2.99692 13.9548 2.92809 13.8318 2.83614C13.7227 2.75455 13.6249 2.65965 13.5408 2.55379C13.4461 2.4345 13.3751 2.29684 13.2333 2.02152L12.8141 1.20801Z"
- stroke="currentColor"
- strokeWidth="1.2"
- strokeLinecap="round"
- strokeLinejoin="round"
- />
- </g>
- <defs>
- <clipPath id="clip0_2352_53058">
- <rect width="16" height="16" fill="currentColor" />
- </clipPath>
- </defs>
- </svg>
- </div>
- <div className="text-[10px] font-[600] iconBreak:hidden block">
- {t('ai', 'AI')} Video
- </div>
+ <div>
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ width="16"
+ height="16"
+ viewBox="0 0 16 16"
+ fill="none"
+ >
+ <g clipPath="url(#clip0_2352_53058)">
+ <path
+ d="M8.06916 14.1663V2.04134M4.97208 14.1663V11.1351M4.97208 5.07259V2.04134M11.1662 14.1663V11.1351M9.09973 2.02152L4.8482 2.04134C3.80748 2.04134 3.28712 2.04134 2.88962 2.23957C2.53997 2.41394 2.25569 2.69218 2.07754 3.0344C1.875 3.42345 1.875 3.93275 1.875 4.95134L1.875 11.2563C1.875 12.2749 1.875 12.7842 2.07754 13.1733C2.25569 13.5155 2.53997 13.7937 2.88962 13.9681C3.28712 14.1663 3.80748 14.1663 4.8482 14.1663H11.2901C12.3308 14.1663 12.8512 14.1663 13.2487 13.9681C13.5984 13.7937 13.8826 13.5155 14.0608 13.1733C14.2633 12.7842 14.2633 12.2749 14.2633 11.2563V7.61426M1.875 5.07259L9.09973 5.06116M1.875 11.1351H14.2633M12.8141 1.20801L12.3949 2.02152C12.253 2.29684 12.1821 2.4345 12.0873 2.55379C12.0032 2.65965 11.9054 2.75455 11.7963 2.83614C11.6734 2.92809 11.5315 2.99692 11.2478 3.13458L10.4094 3.54134L11.2478 3.9481C11.5315 4.08576 11.6734 4.15459 11.7963 4.24654C11.9054 4.32814 12.0032 4.42303 12.0873 4.52889C12.1821 4.64818 12.253 4.78584 12.3949 5.06116L12.8141 5.87467L13.2333 5.06116C13.3751 4.78584 13.4461 4.64818 13.5408 4.52889C13.6249 4.42303 13.7227 4.32814 13.8318 4.24654C13.9548 4.15459 14.0966 4.08576 14.3804 3.9481L15.2188 3.54134L14.3804 3.13458C14.0966 2.99692 13.9548 2.92809 13.8318 2.83614C13.7227 2.75455 13.6249 2.65965 13.5408 2.55379C13.4461 2.4345 13.3751 2.29684 13.2333 2.02152L12.8141 1.20801Z"
+ stroke="currentColor"
+ strokeWidth="1.2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ </g>
+ <defs>
+ <clipPath id="clip0_2352_53058">
+ <rect width="16" height="16" fill="currentColor" />
+ </clipPath>
+ </defs>
+ </svg>
</div>
- </div>
- {value.length >= 30 && !loading && (
- <div className="text-[12px] -mt-[10px] w-[200px] absolute bottom-[100%] z-[500] start-0 hidden group-hover:block">
- <ul className="cursor-pointer rounded-[4px] border border-dashed border-newBgLineColor bg-newColColor mt-[3px] p-[5px]">
- {data.map((p: any) => (
- <li
- onClick={generateVideo(p)}
- key={p.identifier}
- className="hover:bg-sixth"
- >
- {p.title}
- </li>
- ))}
- </ul>
+ <div className="text-[10px] font-[600] iconBreak:hidden block">
+ {t('ai', 'AI')} Video
</div>
- )}
+ </div>
</div>
- </>
+ </div>
);
};
diff --git a/libraries/nestjs-libraries/src/agent/agent.graph.service.ts b/libraries/nestjs-libraries/src/agent/agent.graph.service.ts
index 8a149fea2..567708cc9 100644
--- a/libraries/nestjs-libraries/src/agent/agent.graph.service.ts
+++ b/libraries/nestjs-libraries/src/agent/agent.graph.service.ts
@@ -29,7 +29,7 @@ const model = new ChatOpenAI({
const dalle = new DallEAPIWrapper({
apiKey: process.env.OPENAI_API_KEY || 'sk-proj-',
- model: 'dall-e-3',
+ model: 'chatgpt-image-latest',
});
interface WorkflowChannelsState {
diff --git a/libraries/nestjs-libraries/src/database/prisma/autopost/autopost.service.ts b/libraries/nestjs-libraries/src/database/prisma/autopost/autopost.service.ts
index c8132847f..9b7f9e9ee 100644
--- a/libraries/nestjs-libraries/src/database/prisma/autopost/autopost.service.ts
+++ b/libraries/nestjs-libraries/src/database/prisma/autopost/autopost.service.ts
@@ -43,7 +43,7 @@ const model = new ChatOpenAI({
const dalle = new DallEAPIWrapper({
apiKey: process.env.OPENAI_API_KEY || 'sk-proj-',
- model: 'gpt-image-1',
+ model: 'chatgpt-image-latest',
});
const generateContent = z.object({
diff --git a/libraries/nestjs-libraries/src/database/prisma/media/media.service.ts b/libraries/nestjs-libraries/src/database/prisma/media/media.service.ts
index a7b4f510d..2b9f39cfb 100644
--- a/libraries/nestjs-libraries/src/database/prisma/media/media.service.ts
+++ b/libraries/nestjs-libraries/src/database/prisma/media/media.service.ts
@@ -45,7 +45,7 @@ export class MediaService {
prompt = await this._openAi.generatePromptForPicture(prompt);
console.log('Prompt:', prompt);
}
- return this._openAi.generateImage(prompt, !!generatePromptFirst);
+ return this._openAi.generateImage(prompt);
}
);
diff --git a/libraries/nestjs-libraries/src/openai/openai.service.ts b/libraries/nestjs-libraries/src/openai/openai.service.ts
index 7e4778921..d1eb8ac5d 100644
--- a/libraries/nestjs-libraries/src/openai/openai.service.ts
+++ b/libraries/nestjs-libraries/src/openai/openai.service.ts
@@ -18,17 +18,18 @@ const VoicePrompt = z.object({
@Injectable()
export class OpenaiService {
- async generateImage(prompt: string, isUrl: boolean, isVertical = false) {
+ async generateImage(prompt: string, isVertical = false) {
+ // gpt-image models always return base64 (b64_json) and do not accept the
+ // `response_format` parameter, unlike the deprecated dall-e-3.
const generate = (
await openai.images.generate({
prompt,
- response_format: isUrl ? 'url' : 'b64_json',
- model: 'dall-e-3',
- ...(isVertical ? { size: '1024x1792' } : {}),
+ model: 'chatgpt-image-latest',
+ size: isVertical ? '1024x1536' : '1024x1024',
})
).data[0];
- return isUrl ? generate.url : generate.b64_json;
+ return generate.b64_json;
}
async generatePromptForPicture(prompt: string) {
diff --git a/libraries/nestjs-libraries/src/upload/cloudflare.storage.ts b/libraries/nestjs-libraries/src/upload/cloudflare.storage.ts
index 032646deb..218d40eed 100644
--- a/libraries/nestjs-libraries/src/upload/cloudflare.storage.ts
+++ b/libraries/nestjs-libraries/src/upload/cloudflare.storage.ts
@@ -8,6 +8,7 @@ import { IUploadProvider } from './upload.interface';
import axios from 'axios';
import { isSafePublicHttpsUrl } from '@gitroom/nestjs-libraries/dtos/webhooks/webhook.url.validator';
import { ssrfSafeDispatcher } from '@gitroom/nestjs-libraries/dtos/webhooks/ssrf.safe.dispatcher';
+import { parseDataUrl } from '@gitroom/nestjs-libraries/upload/data.url';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { fromBuffer } = require('file-type');
@@ -77,14 +78,21 @@ class CloudflareStorage implements IUploadProvider {
}
async uploadSimple(path: string) {
- if (!(await isSafePublicHttpsUrl(path))) {
- throw new Error('Unsafe URL');
+ const dataUrl = path.startsWith('data:') ? parseDataUrl(path) : null;
+
+ let body: Buffer;
+ if (dataUrl) {
+ body = dataUrl.buffer;
+ } else {
+ if (!(await isSafePublicHttpsUrl(path))) {
+ throw new Error('Unsafe URL');
+ }
+ const loadImage = await fetch(path, {
+ // @ts-ignore β€” undici option, not in lib.dom fetch types
+ dispatcher: ssrfSafeDispatcher,
+ });
+ body = Buffer.from(await loadImage.arrayBuffer());
}
- const loadImage = await fetch(path, {
- // @ts-ignore β€” undici option, not in lib.dom fetch types
- dispatcher: ssrfSafeDispatcher,
- });
- const body = Buffer.from(await loadImage.arrayBuffer());
const detected = await fromBuffer(body);
if (!detected || !ALLOWED_MIME_TYPES.has(detected.mime)) {
throw new Error('Unsupported file type.');
diff --git a/libraries/nestjs-libraries/src/upload/data.url.ts b/libraries/nestjs-libraries/src/upload/data.url.ts
new file mode 100644
index 000000000..2a56c943b
--- /dev/null
+++ b/libraries/nestjs-libraries/src/upload/data.url.ts
@@ -0,0 +1,26 @@
+/**
+ * Parses a `data:` URL into a Buffer and its mime type.
+ *
+ * gpt-image models only return base64 image data (never a URL), so the image
+ * generation flow hands `uploadSimple` a data URL instead of a remote URL.
+ *
+ * Returns null when the value is not a valid data URL.
+ */
+export function parseDataUrl(
+ value: string
+): { buffer: Buffer; mime: string } | null {
+ const match = /^data:([^;,]+)?(;base64)?,([\s\S]*)$/.exec(value);
+ if (!match) {
+ return null;
+ }
+
+ const mime = match[1] || 'application/octet-stream';
+ const isBase64 = !!match[2];
+ const data = match[3];
+
+ const buffer = isBase64
+ ? Buffer.from(data, 'base64')
+ : Buffer.from(decodeURIComponent(data), 'utf-8');
+
+ return { buffer, mime };
+}
diff --git a/libraries/nestjs-libraries/src/upload/local.storage.ts b/libraries/nestjs-libraries/src/upload/local.storage.ts
index 3c064f693..b237aaf7e 100644
--- a/libraries/nestjs-libraries/src/upload/local.storage.ts
+++ b/libraries/nestjs-libraries/src/upload/local.storage.ts
@@ -1,10 +1,8 @@
import { IUploadProvider } from './upload.interface';
import { mkdirSync, unlink, writeFileSync } from 'fs';
-// @ts-ignore
-import mime from 'mime';
-import { extname } from 'path';
import { isSafePublicHttpsUrl } from '@gitroom/nestjs-libraries/dtos/webhooks/webhook.url.validator';
import { ssrfSafeDispatcher } from '@gitroom/nestjs-libraries/dtos/webhooks/ssrf.safe.dispatcher';
+import { parseDataUrl } from '@gitroom/nestjs-libraries/upload/data.url';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { fromBuffer } = require('file-type');
@@ -26,19 +24,32 @@ export class LocalStorage implements IUploadProvider {
constructor(private uploadDirectory: string) {}
async uploadSimple(path: string) {
- if (!(await isSafePublicHttpsUrl(path))) {
- throw new Error('Unsafe URL');
+ const dataUrl = path.startsWith('data:') ? parseDataUrl(path) : null;
+
+ let body: Buffer;
+ if (dataUrl) {
+ body = dataUrl.buffer;
+ } else {
+ if (!(await isSafePublicHttpsUrl(path))) {
+ throw new Error('Unsafe URL');
+ }
+ const loadImage = await fetch(path, {
+ // @ts-ignore β€” undici option, not in lib.dom fetch types
+ dispatcher: ssrfSafeDispatcher,
+ });
+ body = Buffer.from(await loadImage.arrayBuffer());
}
- const loadImage = await fetch(path, {
- // @ts-ignore β€” undici option, not in lib.dom fetch types
- dispatcher: ssrfSafeDispatcher,
- });
- const contentType =
- loadImage?.headers?.get('content-type') ||
- loadImage?.headers?.get('Content-Type');
- const findExtension = mime.getExtension(contentType) ||
- path.split('?')[0].split('#')[0].split('.').pop() ||
- 'bin';
+
+ // Never trust the claimed mime/extension (data URL header, remote
+ // content-type, or URL path): sniff the real type from the bytes and
+ // only accept the allow-list, otherwise an attacker could write an
+ // arbitrary file (e.g. .html/.svg with embedded script) into the
+ // publicly served uploads directory on the app's own origin.
+ const detected = await fromBuffer(body);
+ if (!detected || !LOCAL_STORAGE_ALLOWED_MIME.has(detected.mime)) {
+ throw new Error('Unsupported file type.');
+ }
+ const findExtension = detected.ext;
const now = new Date();
const year = now.getFullYear();
@@ -57,7 +68,7 @@ export class LocalStorage implements IUploadProvider {
const filePath = `${dir}/${randomName}.${findExtension}`;
const publicPath = `${innerPath}/${randomName}.${findExtension}`;
// Logic to save the file to the filesystem goes here
- writeFileSync(filePath, Buffer.from(await loadImage.arrayBuffer()));
+ writeFileSync(filePath, body);
return process.env.FRONTEND_URL + '/uploads' + publicPath;
}