initial commit

Signed-off-by: ale <ale@manalejandro.com>
Este commit está contenido en:
ale
2025-12-04 00:58:40 +01:00
padre d0c05d13b1
commit 1b51f5a171
Se han modificado 18 ficheros con 3013 adiciones y 6626 borrados

44
app/api/health/route.ts Archivo normal
Ver fichero

@@ -0,0 +1,44 @@
import { NextResponse } from 'next/server';
import { esClient, INDEX_NAME } from '@/lib/elasticsearch';
export async function GET() {
try {
// Check Elasticsearch connection
const health = await esClient.cluster.health({});
// Check if index exists
const indexExists = await esClient.indices.exists({ index: INDEX_NAME });
// Get index stats if exists
let stats = null;
if (indexExists) {
const statsResponse = await esClient.indices.stats({ index: INDEX_NAME });
stats = {
documentCount: statsResponse._all?.primaries?.docs?.count || 0,
indexSize: statsResponse._all?.primaries?.store?.size_in_bytes || 0
};
}
return NextResponse.json({
status: 'ok',
elasticsearch: {
cluster: health.cluster_name,
status: health.status,
},
index: {
exists: indexExists,
name: INDEX_NAME,
stats
}
});
} catch (error) {
console.error('Health check error:', error);
return NextResponse.json(
{
status: 'error',
error: error instanceof Error ? error.message : 'Unknown error'
},
{ status: 503 }
);
}
}

148
app/api/search/route.ts Archivo normal
Ver fichero

@@ -0,0 +1,148 @@
import { NextRequest, NextResponse } from 'next/server';
import { esClient, INDEX_NAME, initializeIndex } from '@/lib/elasticsearch';
import { generateHashes, detectHashType, isHash } from '@/lib/hash';
export async function POST(request: NextRequest) {
try {
const { query } = await request.json();
if (!query || typeof query !== 'string') {
return NextResponse.json(
{ error: 'Query parameter is required' },
{ status: 400 }
);
}
// Ensure index exists
await initializeIndex();
const cleanQuery = query.trim().split(/\s+/)[0];
if (!cleanQuery) {
return NextResponse.json(
{ error: 'Invalid query: only whitespace provided' },
{ status: 400 }
);
}
const cleanQueryLower = cleanQuery.toLowerCase();
const hashType = detectHashType(cleanQueryLower);
if (hashType) {
// Query is a hash - search for it in Elasticsearch
const searchResponse = await esClient.search({
index: INDEX_NAME,
query: {
term: {
[hashType]: hashType === 'bcrypt' ? cleanQuery : cleanQueryLower
}
}
});
const hits = searchResponse.hits.hits;
if (hits.length > 0) {
// Found matching plaintext
return NextResponse.json({
found: true,
hashType,
hash: cleanQuery,
results: hits.map((hit: any) => ({
plaintext: hit._source.plaintext,
hashes: {
md5: hit._source.md5,
sha1: hit._source.sha1,
sha256: hit._source.sha256,
sha512: hit._source.sha512,
bcrypt: hit._source.bcrypt,
}
}))
});
} else {
// Hash not found in database
return NextResponse.json({
found: false,
hashType,
hash: cleanQuery,
message: 'Hash not found in database'
});
}
} else {
// Query is plaintext - check if it already exists first
const existsResponse = await esClient.search({
index: INDEX_NAME,
query: {
term: {
'plaintext.keyword': cleanQuery
}
}
} as any);
let hashes;
if (existsResponse.hits.hits.length > 0) {
// Plaintext found, retrieve existing hashes
const existingDoc = existsResponse.hits.hits[0]._source as any;
hashes = {
md5: existingDoc.md5,
sha1: existingDoc.sha1,
sha256: existingDoc.sha256,
sha512: existingDoc.sha512,
bcrypt: existingDoc.bcrypt,
};
} else {
// Plaintext not found, generate hashes and check if any hash already exists
hashes = await generateHashes(cleanQuery);
const hashExistsResponse = await esClient.search({
index: INDEX_NAME,
query: {
bool: {
should: [
{ term: { md5: hashes.md5 } },
{ term: { sha1: hashes.sha1 } },
{ term: { sha256: hashes.sha256 } },
{ term: { sha512: hashes.sha512 } },
],
minimum_should_match: 1
}
}
} as any);
if (hashExistsResponse.hits.hits.length === 0) {
// No duplicates found, insert new document
await esClient.index({
index: INDEX_NAME,
document: {
...hashes,
created_at: new Date().toISOString()
}
});
// Refresh index to make the document searchable immediately
await esClient.indices.refresh({ index: INDEX_NAME });
}
}
return NextResponse.json({
found: true,
isPlaintext: true,
plaintext: cleanQuery,
wasGenerated: existsResponse.hits.hits.length === 0,
hashes: {
md5: hashes.md5,
sha1: hashes.sha1,
sha256: hashes.sha256,
sha512: hashes.sha512,
bcrypt: hashes.bcrypt,
}
});
}
} catch (error) {
console.error('Search error:', error);
return NextResponse.json(
{ error: 'Internal server error', details: error instanceof Error ? error.message : 'Unknown error' },
{ status: 500 }
);
}
}

Ver fichero

@@ -1,65 +1,273 @@
import Image from "next/image";
'use client';
import { useState } from 'react';
import { Search, Copy, Check, Hash, Key, AlertCircle, Loader2 } from 'lucide-react';
interface SearchResult {
found: boolean;
hashType?: string;
hash?: string;
isPlaintext?: boolean;
plaintext?: string;
wasGenerated?: boolean;
hashes?: {
md5: string;
sha1: string;
sha256: string;
sha512: string;
bcrypt: string;
};
results?: Array<{
plaintext: string;
hashes: {
md5: string;
sha1: string;
sha256: string;
sha512: string;
bcrypt: string;
};
}>;
message?: string;
}
export default function Home() {
const [query, setQuery] = useState('');
const [result, setResult] = useState<SearchResult | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const [copiedField, setCopiedField] = useState<string | null>(null);
const handleSearch = async (e: React.FormEvent) => {
e.preventDefault();
if (!query.trim()) return;
setLoading(true);
setError('');
setResult(null);
try {
const response = await fetch('/api/search', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query: query.trim() })
});
if (!response.ok) {
throw new Error('Search failed');
}
const data = await response.json();
setResult(data);
} catch (err) {
setError('Failed to perform search. Please check your connection.');
} finally {
setLoading(false);
}
};
const copyToClipboard = (text: string, field: string) => {
navigator.clipboard.writeText(text);
setCopiedField(field);
setTimeout(() => setCopiedField(null), 2000);
};
const HashDisplay = ({ label, value, field }: { label: string; value: string; field: string }) => (
<div className="bg-gray-50 rounded-lg p-4 border border-gray-200">
<div className="flex items-center justify-between mb-2">
<span className="text-sm font-semibold text-gray-700 uppercase">{label}</span>
<button
onClick={() => copyToClipboard(value, field)}
className="text-gray-500 hover:text-gray-700 transition-colors"
title="Copy to clipboard"
>
{copiedField === field ? (
<Check className="w-4 h-4 text-green-600" />
) : (
<Copy className="w-4 h-4" />
)}
</button>
</div>
<code className="text-xs font-mono break-all text-gray-900">{value}</code>
</div>
);
return (
<div className="flex min-h-screen items-center justify-center bg-zinc-50 font-sans dark:bg-black">
<main className="flex min-h-screen w-full max-w-3xl flex-col items-center justify-between py-32 px-16 bg-white dark:bg-black sm:items-start">
<Image
className="dark:invert"
src="/next.svg"
alt="Next.js logo"
width={100}
height={20}
priority
/>
<div className="flex flex-col items-center gap-6 text-center sm:items-start sm:text-left">
<h1 className="max-w-xs text-3xl font-semibold leading-10 tracking-tight text-black dark:text-zinc-50">
To get started, edit the page.tsx file.
<div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-purple-50">
<div className="container mx-auto px-4 py-12 max-w-4xl">
{/* Header */}
<div className="text-center mb-12">
<div className="flex items-center justify-center mb-4">
<div className="bg-gradient-to-r from-blue-600 to-purple-600 p-4 rounded-2xl shadow-lg">
<Hash className="w-12 h-12 text-white" />
</div>
</div>
<h1 className="text-5xl font-bold bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent mb-3">
Hasher
</h1>
<p className="max-w-md text-lg leading-8 text-zinc-600 dark:text-zinc-400">
Looking for a starting point or more instructions? Head over to{" "}
<a
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
className="font-medium text-zinc-950 dark:text-zinc-50"
>
Templates
</a>{" "}
or the{" "}
<a
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
className="font-medium text-zinc-950 dark:text-zinc-50"
>
Learning
</a>{" "}
center.
<p className="text-gray-600 text-lg">
Search for hashes or generate them from plaintext
</p>
<p className="text-sm text-gray-500 mt-2">
Supports MD5, SHA1, SHA256, SHA512, and Bcrypt
</p>
</div>
<div className="flex flex-col gap-4 text-base font-medium sm:flex-row">
<a
className="flex h-12 w-full items-center justify-center gap-2 rounded-full bg-foreground px-5 text-background transition-colors hover:bg-[#383838] dark:hover:bg-[#ccc] md:w-[158px]"
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
className="dark:invert"
src="/vercel.svg"
alt="Vercel logomark"
width={16}
height={16}
{/* Search Form */}
<form onSubmit={handleSearch} className="mb-8">
<div className="relative">
<input
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Enter a hash or plaintext..."
className="w-full px-6 py-4 pr-14 text-lg rounded-2xl border-2 border-gray-200 focus:border-blue-500 focus:ring-4 focus:ring-blue-100 outline-none transition-all shadow-sm"
/>
Deploy Now
</a>
<a
className="flex h-12 w-full items-center justify-center rounded-full border border-solid border-black/[.08] px-5 transition-colors hover:border-transparent hover:bg-black/[.04] dark:border-white/[.145] dark:hover:bg-[#1a1a1a] md:w-[158px]"
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
Documentation
</a>
</div>
</main>
<button
type="submit"
disabled={loading || !query.trim()}
className="absolute right-2 top-1/2 -translate-y-1/2 bg-gradient-to-r from-blue-600 to-purple-600 text-white p-3 rounded-xl hover:shadow-lg disabled:opacity-50 disabled:cursor-not-allowed transition-all"
>
{loading ? (
<Loader2 className="w-6 h-6 animate-spin" />
) : (
<Search className="w-6 h-6" />
)}
</button>
</div>
</form>
{/* Error Message */}
{error && (
<div className="bg-red-50 border-2 border-red-200 rounded-2xl p-4 mb-8 flex items-start gap-3">
<AlertCircle className="w-6 h-6 text-red-600 flex-shrink-0 mt-0.5" />
<div>
<h3 className="font-semibold text-red-900 mb-1">Error</h3>
<p className="text-red-700">{error}</p>
</div>
</div>
)}
{/* Results */}
{result && (
<div className="bg-white rounded-2xl shadow-xl p-8 border border-gray-100">
{result.isPlaintext ? (
<>
<div className="flex items-center gap-3 mb-6 pb-6 border-b border-gray-200">
<div className="bg-green-100 p-3 rounded-xl">
<Key className="w-6 h-6 text-green-600" />
</div>
<div>
<h2 className="text-2xl font-bold text-gray-900">Generated Hashes</h2>
<p className="text-gray-600">For plaintext: <span className="font-mono font-semibold">{result.plaintext}</span></p>
</div>
</div>
<div className="space-y-4">
<HashDisplay label="MD5" value={result.hashes!.md5} field="md5-gen" />
<HashDisplay label="SHA1" value={result.hashes!.sha1} field="sha1-gen" />
<HashDisplay label="SHA256" value={result.hashes!.sha256} field="sha256-gen" />
<HashDisplay label="SHA512" value={result.hashes!.sha512} field="sha512-gen" />
<HashDisplay label="Bcrypt" value={result.hashes!.bcrypt} field="bcrypt-gen" />
</div>
{result.wasGenerated && (
<div className="mt-6 bg-blue-50 border border-blue-200 rounded-xl p-4">
<p className="text-sm text-blue-800">
These hashes have been saved to the database for future lookups.
</p>
</div>
)}
</>
) : result.found && result.results && result.results.length > 0 ? (
<>
<div className="flex items-center gap-3 mb-6 pb-6 border-b border-gray-200">
<div className="bg-green-100 p-3 rounded-xl">
<Check className="w-6 h-6 text-green-600" />
</div>
<div>
<h2 className="text-2xl font-bold text-gray-900">Hash Found!</h2>
<p className="text-gray-600">Type: <span className="font-semibold uppercase">{result.hashType}</span></p>
</div>
</div>
{result.results.map((item, idx) => (
<div key={idx} className="mb-6 last:mb-0">
<div className="bg-green-50 border-2 border-green-200 rounded-xl p-5 mb-4">
<div className="flex items-center justify-between mb-2">
<span className="text-sm font-semibold text-green-900 uppercase">Plaintext</span>
<button
onClick={() => copyToClipboard(item.plaintext, `plaintext-${idx}`)}
className="text-green-700 hover:text-green-900 transition-colors"
>
{copiedField === `plaintext-${idx}` ? (
<Check className="w-4 h-4" />
) : (
<Copy className="w-4 h-4" />
)}
</button>
</div>
<div className="text-2xl font-bold text-green-900 font-mono break-all">
{item.plaintext}
</div>
</div>
<div className="space-y-3">
<HashDisplay label="MD5" value={item.hashes.md5} field={`md5-${idx}`} />
<HashDisplay label="SHA1" value={item.hashes.sha1} field={`sha1-${idx}`} />
<HashDisplay label="SHA256" value={item.hashes.sha256} field={`sha256-${idx}`} />
<HashDisplay label="SHA512" value={item.hashes.sha512} field={`sha512-${idx}`} />
<HashDisplay label="Bcrypt" value={item.hashes.bcrypt} field={`bcrypt-${idx}`} />
</div>
</div>
))}
</>
) : (
<>
<div className="flex items-center gap-3 mb-4">
<div className="bg-yellow-100 p-3 rounded-xl">
<AlertCircle className="w-6 h-6 text-yellow-600" />
</div>
<div>
<h2 className="text-2xl font-bold text-gray-900">Hash Not Found</h2>
<p className="text-gray-600">Type: <span className="font-semibold uppercase">{result.hashType}</span></p>
</div>
</div>
<div className="bg-yellow-50 border border-yellow-200 rounded-xl p-4">
<p className="text-yellow-800">
This hash is not in our database. Try searching with plaintext to generate hashes.
</p>
</div>
</>
)}
</div>
)}
{/* Info Cards */}
{!result && !loading && (
<div className="grid md:grid-cols-2 gap-6 mt-12">
<div className="bg-white rounded-2xl p-6 shadow-lg border border-gray-100">
<div className="bg-blue-100 w-12 h-12 rounded-xl flex items-center justify-center mb-4">
<Search className="w-6 h-6 text-blue-600" />
</div>
<h3 className="text-xl font-bold text-gray-900 mb-2">Search Hashes</h3>
<p className="text-gray-600">
Enter a hash to find its original plaintext value. Our database contains commonly used words and phrases.
</p>
</div>
<div className="bg-white rounded-2xl p-6 shadow-lg border border-gray-100">
<div className="bg-purple-100 w-12 h-12 rounded-xl flex items-center justify-center mb-4">
<Hash className="w-6 h-6 text-purple-600" />
</div>
<h3 className="text-xl font-bold text-gray-900 mb-2">Generate Hashes</h3>
<p className="text-gray-600">
Enter any plaintext to instantly generate MD5, SHA1, SHA256, SHA512, and Bcrypt hashes. Results are saved automatically.
</p>
</div>
</div>
)}
{/* Footer */}
<footer className="mt-16 text-center text-gray-500 text-sm">
<p>Powered by Elasticsearch Built with Next.js</p>
</footer>
</div>
</div>
);
}