check-url-safety.ts90 lines, 2.3 KB
| 1 | "use server"; |
| 2 | |
| 3 | import { GoogleGenerativeAI } from "@google/generative-ai"; |
| 4 | import { ApiResponse } from "@/lib/types"; |
| 5 | |
| 6 | const genAI = new GoogleGenerativeAI(process.env.GOOGLE_GEMINI_API_KEY!); |
| 7 | |
| 8 | export type UrlSafetyCheck = { |
| 9 | isSafe: boolean; |
| 10 | flagged: boolean; |
| 11 | reason: string | null; |
| 12 | category: "safe" | "suspicious" | "malicious" | "inappropriate" | "unknown"; |
| 13 | confidence: number; |
| 14 | }; |
| 15 | |
| 16 | export async function checkUrlSafety( |
| 17 | url: string |
| 18 | ): Promise<ApiResponse<UrlSafetyCheck>> { |
| 19 | try { |
| 20 | // validate URL Format |
| 21 | try { |
| 22 | new URL(url); |
| 23 | } catch (error) { |
| 24 | return { |
| 25 | success: false, |
| 26 | error: "Invalid URL format", |
| 27 | }; |
| 28 | } |
| 29 | |
| 30 | if (!process.env.GOOGLE_GEMINI_API_KEY) { |
| 31 | console.log("Missing Google Gemini API Key"); |
| 32 | return { |
| 33 | success: true, |
| 34 | data: { |
| 35 | isSafe: true, |
| 36 | flagged: false, |
| 37 | reason: null, |
| 38 | category: "unknown", |
| 39 | confidence: 0, |
| 40 | }, |
| 41 | }; |
| 42 | } |
| 43 | |
| 44 | const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" }); |
| 45 | |
| 46 | const prompt = ` |
| 47 | Analyze this URL for safety concerns: "${url}" |
| 48 | |
| 49 | Consider the following aspects: |
| 50 | 1. Is it a known phishing site? |
| 51 | 2. Does it contain malware or suspicious redirects? |
| 52 | 3. Is it associated with scams or fraud? |
| 53 | 4. Does it contain inappropriate content (adult, violence, etc.)? |
| 54 | 5. Is the domain suspicious or newly registered? |
| 55 | |
| 56 | Respond in JSON format with the following structure: |
| 57 | { |
| 58 | "isSafe": boolean, |
| 59 | "flagged": boolean, |
| 60 | "reason": string or null, |
| 61 | "category": "safe" | "suspicious" | "malicious" | "inappropriate" | "unknown", |
| 62 | "confidence": number between 0 and 1 |
| 63 | } |
| 64 | |
| 65 | Only respond with the JSON object, no additional text. |
| 66 | `; |
| 67 | |
| 68 | const result = await model.generateContent(prompt); |
| 69 | const response = result.response; |
| 70 | const text = response.text(); |
| 71 | |
| 72 | const jsonMatch = text.match(/\{[\s\S]*\}/); |
| 73 | if (!jsonMatch) { |
| 74 | throw new Error("Failed to parse JSON response"); |
| 75 | } |
| 76 | |
| 77 | const jsonResponse = JSON.parse(jsonMatch[0]) as UrlSafetyCheck; |
| 78 | |
| 79 | return { |
| 80 | success: true, |
| 81 | data: jsonResponse, |
| 82 | }; |
| 83 | } catch (error) { |
| 84 | console.error(error); |
| 85 | return { |
| 86 | success: false, |
| 87 | error: "Failed to check URL safety" |
| 88 | }; |
| 89 | } |
| 90 | } |