## AI Master Prompt: Veri Kalkanı (Data Shield) - Next.js MVP Application
**PROJECT OVERVIEW:**
'Veri Kalkanı' (Data Shield) is a revolutionary SaaS platform designed to address the growing concerns around centralized digital identity management, particularly in light of new regulations like Germany's eIDAS implementation that may force users to rely on Apple/Google accounts for authentication. The core problem this application solves is the potential loss of user control and data privacy when digital identities are tied to large tech corporations. Our value proposition is to provide users with a secure, decentralized, and self-sovereign digital identity solution. Users can create, manage, and utilize their digital identities without depending on Big Tech intermediaries, ensuring full control over their personal data and authentication processes. This MVP will focus on enabling secure identity creation and management, with initial integrations to simulate eIDAS-compliant authentication flows, bypassing the need for Apple/Google accounts.
**TECH STACK:**
* **Framework:** Next.js (App Router)
* **Language:** TypeScript
* **Styling:** Tailwind CSS
* **Database ORM:** Drizzle ORM
* **Database:** PostgreSQL (using Vercel Postgres or Supabase)
* **Authentication:** NextAuth.js (for managing user sessions and credentials)
* **UI Components:** shadcn/ui (for accessible, reusable components)
* **State Management:** React Context API / Zustand (for global state, component-level state with useState/useReducer)
* **Form Handling:** React Hook Form + Zod (for validation)
* **Utility Libraries:** Date-fns, clsx, lodash (as needed)
* **Deployment:** Vercel
**DATABASE SCHEMA (PostgreSQL with Drizzle ORM):**
1. **`users` Table:**
* `id` (UUID, primary key)
* `email` (VARCHAR, unique, not null)
* `hashedPassword` (VARCHAR, not null) - *For local credential login*
* `name` (VARCHAR)
* `createdAt` (TIMESTAMPZ, default now())
* `updatedAt` (TIMESTAMPZ, default now())
2. **`accounts` Table (for NextAuth.js integration - OAuth/Credentials providers):
* `id` (BIGSERIAL, primary key)
* `userId` (UUID, foreign key to `users.id`, not null)
* `type` (VARCHAR, not null) - *e.g., "oauth", "credentials"*
* `provider` (VARCHAR, not null) - *e.g., "google", "credentials"*
* `providerAccountId` (VARCHAR, not null)
* `refresh_token` (TEXT)
* `access_token` (TEXT)
* `expires_at` (BIGINT)
* `token_type` (VARCHAR)
* `scope` (VARCHAR)
* `id_token` (TEXT)
* `session_token` (VARCHAR, unique, not null)
3. **`digitalIdentities` Table:**
* `id` (UUID, primary key)
* `userId` (UUID, foreign key to `users.id`, not null)
* `identityName` (VARCHAR, not null) - *e.g., "My Primary ID"*
* `publicKey` (TEXT, not null) - *Stores the user's public key*
* `encryptedPrivateKey` (TEXT, not null) - *Stores the user's private key, encrypted with a key derived from their password/passphrase*
* `status` (VARCHAR, default 'active') - *e.g., 'active', 'revoked'*
* `createdAt` (TIMESTAMPZ, default now())
* `updatedAt` (TIMESTAMPZ, default now())
4. **`dataPermissions` Table:**
* `id` (UUID, primary key)
* `digitalIdentityId` (UUID, foreign key to `digitalIdentities.id`, not null)
* `serviceName` (VARCHAR, not null) - *Name of the service requesting data*
* `requestedData` (JSONB, not null) - *Details of the data fields requested (e.g., `["name", "email", "dob"]`)*
* `granted` (BOOLEAN, not null)
* `grantedAt` (TIMESTAMPZ)
* `revokedAt` (TIMESTAMPZ)
* `createdAt` (TIMESTAMPZ, default now())
**Relationships:**
* One `user` can have multiple `digitalIdentities`.
* One `user` can have multiple `accounts` (for different login methods).
* One `digitalIdentity` can have multiple `dataPermissions` granted over time.
**CORE FEATURES & USER FLOW:**
1. **User Authentication (Sign Up/Login):
* **Flow:** User visits the landing page. Clicks 'Sign Up' or 'Login'.
* **Sign Up:** Enters email and password. Password is hashed using bcrypt. A new record is created in the `users` table and an `accounts` record for `credentials` provider.
* **Login:** Enters email and password. System retrieves user by email, compares hashed password. If match, a session is created using NextAuth.js.
* **Credentials:** `credentials` provider in NextAuth.js will handle email/password login.
* **Edge Case:** Invalid credentials, email already exists.
2. **Digital Identity Creation:
* **Flow:** After login, user navigates to 'My Identities' section. Clicks 'Create New Identity'. User is prompted to enter a secure passphrase (this will be used to encrypt the private key).
* **Action:** The frontend generates a new cryptographic key pair (public/private). The private key is encrypted using a key derived from the user's passphrase (e.g., using PBKDF2 or Argon2). The public key and the encrypted private key are sent to the backend.
* **Backend:** Stores the `digitalIdentity` record in the database, linking it to the `userId`. The public key is stored directly, and the encrypted private key is stored in the `encryptedPrivateKey` field.
* **Edge Case:** Passphrase too weak, key generation failure.
3. **Digital Identity Management & Viewing:
* **Flow:** User navigates to 'My Identities'. A list of their created digital identities is displayed.
* **Action:** Clicking an identity shows its details: Identity Name, Public Key (for reference), Status. Options to 'Revoke' or 'Manage Permissions' are available.
* **View Public Key:** User can view and copy their public key.
* **Revoke:** User can choose to revoke an identity. This action updates the `status` in the `digitalIdentities` table to 'revoked'. This is a critical action and should require re-authentication and confirmation.
* **Edge Case:** No identities created yet (show empty state).
4. **Data Permission Management:
* **Flow (Simulated):** User navigates to 'Permissions' or clicks 'Manage Permissions' for a specific identity. A list of services and the data they've requested (or currently have access to) is shown.
* **Action:** For a new request (simulated), the user sees 'Service X requests: [Name, Email]'. User can choose to 'Grant' or 'Deny'.
* **Grant:** A new record is added to the `dataPermissions` table with `granted: true`, `grantedAt` timestamp, and details of requested data. The frontend can then theoretically use the `digitalIdentity`'s private key (after decryption with the passphrase) to sign a token for the service.
* **Deny:** No record is created, or a record with `granted: false` is created.
* **View Existing Permissions:** User can see previously granted/denied permissions and revoke existing grants by clicking a 'Revoke' button next to the permission entry. This updates the `dataPermissions` record with `revokedAt`.
* **Edge Case:** No permissions yet, service requesting sensitive data.
5. **Simulated eIDAS Authentication (Conceptual for MVP):
* **Flow:** User intends to log into a hypothetical 'eGov Service' (simulated via a button/link on the dashboard).
* **Action:** The user is redirected to Data Shield (or a modal appears) prompting them to authenticate using one of their managed Digital Identities. User selects an identity, enters their passphrase to decrypt the private key in the browser (using crypto APIs like Web Crypto API).
* **Signing:** The Data Shield frontend (or a secure enclave if implemented later) uses the decrypted private key to sign a specific challenge or token provided by the 'eGov Service'.
* **Response:** The signed token/challenge is sent back to the 'eGov Service' for verification using the identity's public key.
* **Note:** This part is heavily simplified for the MVP. A real implementation would involve complex protocols like OpenID Connect or SAML with custom adaptations for eIDAS.
**API & DATA FETCHING:**
* **API Routes:** Use Next.js API Routes (App Router `/api/...` structure).
* `/api/auth/*`: Handled by NextAuth.js.
* `/api/identities`: POST (create), GET (list for user), PUT (update - e.g., status), DELETE (revoke).
* `/api/identities/[id]`: GET (details).
* `/api/permissions`: POST (grant/deny - triggered by user action), GET (list for identity).
* `/api/permissions/[id]`: DELETE (revoke).
* `/api/auth/sign`: POST (endpoint to sign data using private key - requires user passphrase input and decryption client-side or via a secure backend process).
* **Data Fetching:** Utilize server components where possible for initial data load. Use client components with `fetch` or libraries like SWR/React Query for dynamic data, mutations, and real-time updates. API routes will interact with Drizzle ORM to query/mutate the PostgreSQL database.
* **Request/Response:** Standard JSON payloads. Use Zod for request validation in API routes and response data typing.
**UI/UX DESIGN & VISUAL IDENTITY:**
* **Design Style:** Minimalist Clean with a touch of futuristic security. Focus on clarity, trust, and ease of use.
* **Color Palette:**
* Primary: Deep Blue (`#0A192F`)
* Secondary: Dark Gray (`#262626`)
* Accent: Electric Cyan (`#64FFDA`)
* Text: Light Gray (`#CCD6F6`), White (`#FFFFFF`)
* Error: Red (`#FF6B6B`)
* **Typography:**.
* Headings: 'Inter', sans-serif (Bold, Semi-bold)
* Body: 'Inter', sans-serif (Regular, Medium)
* **Layout:**.
* Dashboard: Sidebar navigation (dark theme) and main content area.
* Use cards, clear typography, and ample whitespace.
* Responsive: Mobile-first approach. Sidebar collapses into a hamburger menu on smaller screens. Content reflows gracefully.
* **Visual Elements:** Subtle use of abstract geometric shapes, glowing lines, and secure-looking icons. Avoid overly complex or distracting visuals.
**COMPONENT BREAKDOWN (Next.js App Router Structure):
* **`app/layout.tsx`:** Root layout (html, body, Tailwind setup, global providers).
* **`app/page.tsx`:** Landing Page (Marketing content, value proposition, CTA to Sign Up/Login).
* **`app/(auth)/layout.tsx`:** Auth layout (shared UI for login/signup).
* **`app/(auth)/login/page.tsx`:** Login form component.
* **`app/(auth)/signup/page.tsx`:** Signup form component.
* **`app/dashboard/layout.tsx`:** Main dashboard layout with Sidebar Navigation.
* **`app/dashboard/page.tsx`:** Dashboard Overview (Summary of identities, recent activity, quick links).
* **`app/dashboard/identities/page.tsx`:** 'My Identities' Page (List of digital identities, CTA to create new).
* **`app/dashboard/identities/new/page.tsx`:** Create New Identity Form (Input for passphrase, key generation logic).
* **`app/dashboard/identities/[id]/page.tsx`:** Identity Detail Page (View public key, status, manage permissions, revoke options).
* **`app/dashboard/permissions/page.tsx`:** Permissions Management Page (Overview of all granted/pending permissions).
* **`app/dashboard/settings/page.tsx`:** User Settings (Account details, security settings, change password).
* **`app/components/ui/`:** Reusable shadcn/ui components (Button, Input, Card, Dialog, Sheet, etc.).
* **`app/components/auth/`:** Auth-specific components (LoginForm, SignupForm).
* **`app/components/identity/`:** Identity-related components (IdentityListItem, IdentityDetailView, KeyDisplay).
* **`app/components/layout/`:** Layout components (Sidebar, Header, Footer).
* **`app/providers.tsx`:** Context providers (e.g., ThemeProvider, AuthProvider).
**State Management:** Use `useState`, `useReducer` for local component state. Use Zustand or React Context for global state like user authentication status, fetched identity lists, and permission data that needs to be accessed across multiple components or pages.
**ANIMATIONS:**
* **Page Transitions:** Subtle fade-in/fade-out using Next.js's `<AnimatePresence />` if using Framer Motion, or CSS transitions.
* **Button Hovers:** Slight scale-up or background color change on hover (`transition-all duration-200 ease-in-out`).
* **Loading States:** Use spinners or skeleton loaders (e.g., from shadcn/ui) for data fetching operations. Animate opacity and subtle transformations for elements appearing on screen.
* **Form Feedback:** Subtle animations for validation errors (e.g., input border color change, small shake effect).
**EDGE CASES & VALIDATIONS:**
* **Authentication:** Handle incorrect login attempts, password resets (future feature), session expiry, unauthorized access.
* **Identity Creation:** Validate passphrase strength. Handle cryptographic errors during key generation/encryption. Ensure private key encryption is robust.
* **Data Permissions:** Handle scenarios where a user denies permission. Ensure revoked permissions are non-functional. Validate data request formats.
* **Empty States:** Design informative empty states for 'My Identities' and 'Permissions' pages when no data exists.
* **API Errors:** Implement global error handling for API requests. Show user-friendly error messages. Use try-catch blocks diligently.
* **Client-Side Validation:** Use Zod with React Hook Form for all form inputs (email, password, passphrase, etc.).
* **Rate Limiting:** Implement basic rate limiting on API routes (especially auth) to prevent abuse.
**SAMPLE DATA (for Frontend Mocking / Initial State):**
1. **User:**
```json
{
"id": "user-uuid-1234",
"email": "test@example.com",
"name": "Test User"
}
```
2. **Digital Identity (Active):**
```json
{
"id": "identity-uuid-abcd",
"userId": "user-uuid-1234",
"identityName": "Primary German ID",
"publicKey": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE...\n-----END PUBLIC KEY-----",
"status": "active",
"createdAt": "2024-07-26T10:00:00Z"
}
```
3. **Digital Identity (Revoked):**
```json
{
"id": "identity-uuid-efgh",
"userId": "user-uuid-1234",
"identityName": "Old ID",
"publicKey": "...",
"status": "revoked",
"createdAt": "2023-01-15T09:00:00Z"
}
```
4. **Data Permission (Granted):**
```json
{
"id": "permission-uuid-1",
"digitalIdentityId": "identity-uuid-abcd",
"serviceName": "eGov Portal (Test)",
"requestedData": ["fullName", "dateOfBirth", "address"],
"granted": true,
"grantedAt": "2024-07-26T11:30:00Z"
}
```
5. **Data Permission (Pending/Denied - Example Representation):
```json
{
"id": "permission-uuid-2",
"digitalIdentityId": "identity-uuid-abcd",
"serviceName": "Health Service (Test)",
"requestedData": ["medicalRecordNumber"],
"granted": false,
"createdAt": "2024-07-26T11:35:00Z"
}
```
6. **Service Request (Conceptual - For UI Display):
```json
{
"service": "Mü cittadini Kayıt Ofisi",
"dataNeeded": ["Name", "Anmeldung Address", "Date of Birth"],
"requesterPublicKey": "..."
}
```
7. **User with No Identities (Empty State):**
* The 'My Identities' page would display a message like: "Henüz bir dijital kimliğiniz yok. Lütfen yeni bir kimlik oluşturun."
8. **Identity Detail (No Permissions Yet):**
* The 'Permissions' tab/section within the identity detail page would show: "Bu kimlik için henüz bir veri izni verilmedi."
**TURKISH TRANSLATIONS (Key UI Elements):**
* **App Title:** Veri Kalkanı
* **Login:** Giriş Yap
* **Sign Up:** Kayıt Ol
* **Dashboard:** Kontrol Paneli
* **My Identities:** Kimliklerim
* **Create New Identity:** Yeni Kimlik Oluştur
* **Permissions:** İzinler
* **Settings:** Ayarlar
* **Service Name:** Servis Adı
* **Requested Data:** İstenen Veriler
* **Grant Access:** Erişime İzin Ver
* **Deny Access:** Erişimi Reddet
* **Revoke Access:** Erişimi Geri Al
* **Public Key:** Açık Anahtar
* **Encrypted Private Key:** Şifrelenmiş Özel Anahtar
* **Passphrase:** Parola / Parola İfadesi
* **Status:** Durum
* **Active:** Aktif
* **Revoked:** İptal Edildi
* **Save Changes:** Değişiklikleri Kaydet
* **Logout:** Çıkış Yap
* **Search:** Ara
* **Filter:** Filtrele
* **Sort:** Sırala
* **Are you sure?** Emin misiniz?
* **Identity successfully created:** Kimlik başarıyla oluşturuldu.
* **Access granted:** Erişim izni verildi.
* **Access revoked:** Erişim izni geri alındı.
* **Error:** Hata
* **Success:** Başarılı
* **Warning:** Uyarı